Search code examples
javacollectionsjava-8group-by

Group By List of object on multiple fields Java 8


I will have a list of Employee, which will hold 3 attributes - departmentId, employeeId, employeeGroup.

I want to perform group by on Department Id and employee id. The idea is to send the group name of employee with belonging department. Below can be the 3 possible cases:

Case#1: Same department, different employee, different group.

["Dept001", 100, "Admin"]
["Dept001", 101, "Contrator"]

Case#2: Same department, same employee, different group

["Dept001", 100, "Admin"]
["Dept001", 100, "Contrator"]

Case#3: Diff department, diff employee, same group.

["Dept001", 100, "Admin"]
["Dept002", 101, "Admin"]

I have tried below:

Map<String, Set<Employee>> map = new TreeMap<>();

map = myList.stream().collect(Collectors.groupingBy(Employee::getDepartmentId, 
Collectors.toSet()));

Solution

  • Grouping by multiple fields is going to require multiple calls to Collectors#groupingBy. Luckily, the second parameter of the overloaded Collectors#groupingBy method is another Collector, so it can simply be invoked twice.

    Map<String, Map<Integer, Set<Employee>>> map = myList.stream()
        .collect(Collectors.groupingBy(Employee::getDepartmentId, 
            Collectors.groupingBy(Employee::getEmployeeId, Collectors.toSet())));
    

    Note that the value of the Map is another Map; the first of which is keyed with the employees' department ID, and the second is keyed with the employees' employee ID.