Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 convert Map<Department, List<Person>> to Map<Department, List<String>>

Using Collectors.groupingBy() I can easily obtain a Map<Department, List<Person>> - this gives me all the Person objects that are part of a Department:

allPersons.stream().collect(Collectors.groupingBy(Person::getDepartment));

Now I would like to convert the resulting 'multimap' so that it contains all Persons' names and not the Person objects.

One way to achieve this is:

final Map<Department, List<String>> newMap = new HashMap<>();
personsByDepartmentMap.stream
    .forEach((d, lp) -> newMap.put(
         d, lp.stream().map(Person::getName).collect(Collectors.toList())));

Is there a way to achieve this without using the newMap object? Something like

final Map<Department, List<String>> newMap = 
                personsByDepartmentMap.stream().someBigMagic();
like image 358
user1414745 Avatar asked Jan 21 '15 16:01

user1414745


1 Answers

Map<Dept, List<String>> namesInDept
    = peopleInDept.entrySet().stream()
                  .collect(toMap(Map.Entry::getKey, 
                                 e -> e.getValue().stream()
                                                  .map(Person::getName)
                                                  .collect(toList()));
like image 139
Brian Goetz Avatar answered Oct 26 '22 23:10

Brian Goetz