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();
Map<Dept, List<String>> namesInDept
= peopleInDept.entrySet().stream()
.collect(toMap(Map.Entry::getKey,
e -> e.getValue().stream()
.map(Person::getName)
.collect(toList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With