Java 8 – Group Employees by Age

Introduction

Java 8 introduced the Stream API, which provides a functional and powerful way to process collections of data. One common task in data processing is grouping elements based on specific criteria. For instance, in an organization, you may want to group employees by their age. The Stream API, along with Collectors.groupingBy, allows you to perform such grouping operations efficiently and concisely.

In this guide, we will explore how to use Java 8 streams to group employees by age.

Table of Contents

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

Problem Statement

You need to process a list of employees and group them based on their age. This grouping can help in organizing the data and is useful for various analytics, reporting, and management tasks.

Example:

  • Problem: Given a list of Employee objects, group the employees by their age.
  • 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, age, and department.
  2. Group Employees by Age: Use Collectors.groupingBy to group employees by their age.
  3. Print or Use the Grouped Data: Display or utilize the grouped data as needed.

Java Program

Example: Grouping Employees by Age

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 Age
 * Author: https://www.rameshfadatare.com/
 */
public class GroupEmployeesByAgeExample {

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

        // Group employees by age
        Map<Integer, List<Employee>> employeesByAge = employees.stream()
            .collect(Collectors.groupingBy(Employee::getAge));

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

class Employee {
    private String name;
    private int age;
    private String department;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getDepartment() {
        return department;
    }
}

Output

Age: 25
 - Priya (HR)
 - Suman (IT)
Age: 30
 - Amit (IT)
 - Raj (Finance)
Age: 35
 - Kiran (HR)

Explanation

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

Conclusion

Using Java 8’s Stream API, grouping employees by age is both efficient and easy to implement. The groupingBy collector is particularly useful for organizing data based on specific attributes like age. This approach can be adapted to group data by other attributes, such as department, gender, or city. 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