Search code examples
javaguava

Method to convert `List<Employee>` to `Map<Integer,List<Employee>>`


How can I convert List<Employee> to Map<Integer,List<Employee>>.

Group List<Employee> based on depId present in employee Object, Map key is depId.

Is there any method in java.util.* or in Google Guava to convert it with out iterating through list.


Solution

  • With Java 8+, you can use a stream and group by the id:

    List<Employee> list = ...;
    Map<Integer,List<Employee>> map = list.stream()
                                          .collect(Collectors.groupingBy(Employee::getDepId));