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
  • 29,855
  • 12
  • 76
  • 115
Sireesh Vattikuti
  • 1,100
  • 1
  • 8
  • 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
  • 310,138
  • 72
  • 642
  • 762
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);
Xaerxess
  • 26,590
  • 9
  • 85
  • 109