Sireesh Vattikuti Sireesh Vattikuti - 1 month ago 7
Java Question

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

I am looking for a library or method to 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.

Thanks in advance

Answer

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));
Comments