Java 8 – Find the Department with the Highest Number of Employees

Introduction

Java 8 introduced the Stream API, which provides a powerful and concise way to process collections of data. A common task in data processing is identifying the group with the maximum count, such as finding the department with the highest number of employees. The Stream API, combined with Collectors.groupingBy and Collectors.counting, makes this task straightforward and efficient.

In this guide, we will explore how to use Java 8 streams to find the department with the highest number of employees.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example: Finding the Department with the Highest Number of Employees
  • Conclusion

Problem Statement

You need to find the department with the highest number of employees from a list of Employee objects. This operation is useful in scenarios where you need to analyze organizational structure or manage resources effectively.

Example:

  • Problem: Given a list of Employee objects, find the department with the highest number of employees.
  • Goal: Use Java 8’s Stream API to efficiently find the department with the highest number of employees.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name, department, and other relevant attributes.
  2. Group Employees by Department: Use Collectors.groupingBy to group employees by department.
  3. Count Employees in Each Department: Use Collectors.counting to count the number of employees in each department.
  4. Find the Department with the Maximum Employees: Use max to find the department with the highest count.
  5. Handle the Result: Properly handle the result, including potential empty lists.

Java Program

Example: Finding the Department with the Highest Number of Employees

First, define the Employee class with the necessary fields.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.Map.Entry;

/**
 * Java 8 - Find the Department with the Highest Number of Employees
 * Author: https://www.rameshfadatare.com/
 */
public class MaxEmployeesInDepartmentExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", "IT"),
            new Employee("Priya", "HR"),
            new Employee("Raj", "Finance"),
            new Employee("Suman", "IT"),
            new Employee("Kiran", "HR")
        );

        // Group employees by department and count them
        Map<String, Long> employeeCountByDepartment = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));

        // Find the department with the maximum employees
        Optional<Entry<String, Long>> maxDepartment = employeeCountByDepartment.entrySet()
            .stream()
            .max(Map.Entry.comparingByValue());

        // Print the department with the highest number of employees
        if (maxDepartment.isPresent()) {
            System.out.println("Department with the highest number of employees: " 
                + maxDepartment.get().getKey() 
                + " with " 
                + maxDepartment.get().getValue() 
                + " employees.");
        } else {
            System.out.println("No department found.");
        }
    }
}

class Employee {
    private String name;
    private String department;

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

    public String getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }
}

Output

Department with the highest number of employees: IT with 2 employees.

Explanation

  • Employee Class: The Employee class includes fields name and department. The getDepartment() method is used to retrieve the department of the employee.
  • groupingBy(Employee::getDepartment, Collectors.counting()): The Stream API groups employees by department and counts the number of employees in each department using Collectors.counting.
  • max(Map.Entry.comparingByValue()): This finds the entry (department) with the maximum number of employees.
  • Optional<Entry<String, Long>>: The result is wrapped in an Optional to handle the case where the list might be empty. If a department is found, its name and the number of employees are printed.

Conclusion

Using Java 8’s Stream API, finding the department with the highest number of employees is both efficient and straightforward. The combination of groupingBy, counting, and max allows you to group, count, and then find the maximum value in a collection, making it easy to perform such data analysis tasks in Java. This approach can be adapted to find other maximum values, such as the highest salary in a department or the most experienced employees.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top