Java 8 Program to Print the Name of All Departments in the Organization

1. Introduction to the Problem

Hello everyone, welcome back! In this blog post, we’ll learn how to use Java 8 Streams to extract and print the names of all unique departments in an organization. This method can be especially useful in applications where you need to display or analyze organizational data by departments. Let’s get started!

2. Setting Up the Employee Class

We’ll start by creating an Employee class to represent each employee in our organization. This class will contain fields like id, name, gender, and department. We’ll use this class to create a list of employees, which will act as our dataset.

public class Employee {
    private int id;
    private String name;
    private String gender;
    private String department;

    public Employee(int id, String name, String gender, String department) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.department = department;
    }

    // Getter for department
    public String getDepartment() {
        return department;
    }
}

Explanation:

  • The Employee class has attributes like id, name, gender, and department.
  • The getDepartment() method provides access to the department field, which we’ll use to extract department names later in the program.

3. Creating a List of Employees

Now that we have our Employee class, let’s create a sample list of Employee objects. This list will simulate the employee data in our organization, with each employee associated with a specific department.

import java.util.Arrays;
import java.util.List;

public class EmployeeList {

    public static List<Employee> getEmployees() {
        return Arrays.asList(
            new Employee(1, "Amit", "Male", "IT"),
            new Employee(2, "Sita", "Female", "Finance"),
            new Employee(3, "Rahul", "Male", "HR"),
            new Employee(4, "Priya", "Female", "IT"),
            new Employee(5, "Vijay", "Male", "Finance"),
            new Employee(6, "Anjali", "Female", "HR")
        );
    }
}

Explanation:

  • The getEmployees() method returns a list of Employee objects with various departments like "IT," "Finance," and "HR."
  • This list will serve as our data source for extracting unique department names.

4. Extracting and Printing Unique Department Names using Streams

With our data ready, let’s use Java 8 Streams to extract and print the unique department names from the employee list. We’ll use the map() method to get the department names, distinct() to filter out duplicates, and forEach() to print each unique department name.

import java.util.List;

public class DepartmentNames {

    public static void main(String[] args) {
        List<Employee> employees = EmployeeList.getEmployees();

        // Extract and print unique department names
        employees.stream()
                .map(Employee::getDepartment)   // Extract department names
                .distinct()                    // Remove duplicates
                .forEach(System.out::println);  // Print each unique department
    }
}

Output:

IT
Finance
HR

Explanation:

  1. Stream Creation: The program starts by creating a stream from the list of employees.
  2. Mapping with map(): The map(Employee::getDepartment) method extracts the department names from each Employee object, creating a stream of department names.
  3. Filtering with distinct(): The distinct() method filters out duplicate department names, ensuring that each department is listed only once.
  4. Printing with forEach(): Finally, forEach(System.out::println) prints each unique department name.

This approach is efficient and straightforward, leveraging Java 8’s Stream API to handle data extraction, filtering, and output in one streamlined flow.

5. Explanation of Key Stream Methods

Let’s break down the key Stream API methods we used in this example to extract and print department names.

  • map(): The map() method transforms each Employee object in the stream to its department field. In our example, map(Employee::getDepartment) extracts the department name from each Employee.

  • distinct(): The distinct() method removes any duplicate department names from the stream, ensuring that each department is printed only once.

  • forEach(): Finally, forEach(System.out::println) iterates over each unique department name in the stream and prints it to the console.

These three methods work together to provide a simple and powerful way to extract, filter, and display unique values in a collection.

6. Real-World Use Cases

This approach isn’t just limited to department names; it’s applicable to a wide range of real-world scenarios, such as:

  1. Generating lists of unique teams, locations, or roles within an organization.
  2. Displaying unique values in reports, such as different categories, locations, or roles.
  3. Filtering data for analytics, ensuring there are no duplicates in specific fields."

In each of these cases, using Java 8 Streams allows you to efficiently handle data extraction and filtering tasks, making your code cleaner and more readable.

7. Conclusion

In today’s blog post, we learned how to use Java 8 Streams to efficiently extract and print unique department names from a dataset. By leveraging map(), distinct(), and forEach(), we’re able to obtain unique values without duplicates, making our data processing more effective. This approach is powerful for data analysis, reporting, and displaying unique attributes in enterprise applications. 

Comments