Java 8 – Group Employees by City

Introduction

Java 8 introduced the Stream API, which provides a powerful and expressive way to process collections of data. One common task in data processing is grouping elements based on certain criteria. For instance, in an organization, you may need to group employees by the city they work in. The Stream API, along with Collectors.groupingBy, makes this task straightforward and efficient.

In this guide, we will explore how to use Java 8 streams to group employees by the city they work in.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example: Grouping Employees by City
  • Conclusion

Problem Statement

You need to process a list of employees and group them based on the city they work in. This grouping can help organize the data and can be useful for reporting, analytics, and other purposes.

Example:

  • Problem: Given a list of Employee objects, group the employees by the city they work in.
  • Goal: Use Java 8’s Stream API to efficiently perform this grouping operation.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name, city, and department.
  2. Group Employees by City: Use Collectors.groupingBy to group employees by the city they work in.
  3. Print or Use the Grouped Data: Display or utilize the grouped data as needed.

Java Program

Example: Grouping Employees by City

First, define the Employee class with the necessary fields.

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

/**
 * Java 8 - Group Employees by City
 * Author: https://www.rameshfadatare.com/
 */
public class GroupEmployeesByCityExample {

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

        // Group employees by city
        Map<String, List<Employee>> employeesByCity = employees.stream()
            .collect(Collectors.groupingBy(Employee::getCity));

        // Display the grouped data
        employeesByCity.forEach((city, empList) -> {
            System.out.println("City: " + city);
            empList.forEach(employee -> 
                System.out.println(" - " + employee.getName() + " (" + employee.getDepartment() + ")"));
        });
    }
}

class Employee {
    private String name;
    private String city;
    private String department;

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

    public String getName() {
        return name;
    }

    public String getCity() {
        return city;
    }

    public String getDepartment() {
        return department;
    }
}

Output

City: Bangalore
 - Amit (IT)
 - Raj (Finance)
City: Delhi
 - Priya (HR)
 - Kiran (HR)
City: Mumbai
 - Suman (IT)

Explanation

  • Employee Class: The Employee class includes fields name, city, and department. The getCity() method is used to retrieve the city where the employee works.
  • groupingBy(Employee::getCity): The Stream API groups the employees by city using Collectors.groupingBy. This method returns a Map where the key is the city name, and the value is a list of employees in that city.
  • forEach(): The grouped data is printed to the console. For each city, the employees in that city are listed along with their departments.

Conclusion

Using Java 8’s Stream API, grouping employees by city is both efficient and easy to implement. The groupingBy collector is particularly useful for organizing data based on a specific attribute. This approach can be adapted to group data by any other attribute, such as department, job title, or any other characteristic. The flexibility and power of the Stream API make it used for data processing tasks in Java.

Leave a Comment

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

Scroll to Top