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

1. Introduction

This tutorial demonstrates how to utilize Java 8 Streams to list all unique departments in an organization from a collection of employees. We can efficiently process collections by leveraging Java Stream operations to extract distinct department names.

2. Program Steps

1. Define the Employee class.

2. Create a list of Employee objects.

3. Apply Java Stream operations to identify and print all unique departments.

3. Code Program

public class DepartmentPrinter {

    static class Employee {
        String name;
        int age;
        String gender;
        String department;
        String organization;

        Employee(String name, int age, String gender, String department, String organization) {
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.department = department;
            this.organization = organization;
        }

        public String getDepartment() {
            return department;
        }
    }

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit Singh", 34, "Male", "Finance", "Infosys"),
            new Employee("Deepa Patil", 29, "Female", "IT", "TCS"),
            new Employee("Rajesh Kumar", 42, "Male", "Finance", "Infosys"),
            new Employee("Lalitha Bhatt", 28, "Female", "HR", "Wipro"),
            new Employee("Suresh Raina", 30, "Male", "IT", "TCS"),
            new Employee("Gita Saxena", 31, "Female", "Marketing", "Infosys")
        );

        employees.stream()
                 .map(Employee::getDepartment)
                 .distinct()
                 .forEach(System.out::println);
    }
}

Output:

Finance
IT
HR
Marketing

Explanation:

1. The Employee class includes fields for name, age, gender, department, and organization. This setup helps represent employees working in various departments across multiple organizations.

2. A list of Employee objects is initialized, each associated with different departments and organizations.

3. Stream Operations:

- map(Employee::getDepartment): This operation extracts the department name from each Employee object.

- distinct(): Ensures that only unique department names are processed.

- forEach(System.out::println): Prints each unique department name to the console.

4. The console output lists all unique departments among the employees, demonstrating how Streams can simplify extracting and displaying data from collections.

This tutorial effectively showcases the use of Java 8 Streams to handle common data processing tasks like extracting unique values from complex object collections, making it invaluable for applications requiring quick and efficient data analysis.

Comments