Search code examples
javajava-streamcollectors

Java: groupingBy subvalue as value


Let's say, I have an object Person with fields of type FirstName and LastName. Now I also have a List<Person> and I like to use streams.

Now I want to generate a Map<FirstName, List<LastName>> in order to group people with the same first name. How do I go about this without writing much code? My approach so far is

personList
.stream()
.collect(Collectors.groupingBy(
    Person::getFirstName,
    person -> person.getLastName() // this seems to be wrong
));

but it seems this is the wrong way to assign the value of the map. What should I change? Or should I perhaps use .reduce with new HashMap<FirstName, List<LastName>>() as initial value and then aggregate to it by putting elements inside?


Solution

  • personList.stream()
              .collect(Collectors.groupingBy(
                   Person::getFirstName,
                   Collectors.mapping(Person::getLastName, Collectors.toList())));
    

    You are looking for a downstream collector with groupingBy