0

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.

Makyen
  • 31,849
  • 12
  • 86
  • 121
Sireesh Vattikuti
  • 1,180
  • 1
  • 9
  • 21

2 Answers2

10

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));
assylias
  • 321,522
  • 82
  • 660
  • 783
2

If you use Guava and want to use proper collection type, here ListMultimap<Integer, Employee>, use Multimaps#index():

ListMultimap<Integer, Employee> m = Multimaps.index(list, Employee::getDepId);
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112