简体   繁体   中英

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?

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

You are looking for a downstream collector with groupingBy

This should work for you :

Map<String, List<String>> map = personList.stream()
                .collect(Collectors.groupingBy(Person::getFirstName, 
                        Collectors.mapping(Person::getLastName, Collectors.toList())));

I think you are looking for something like this:

Map<String, Map<String, List>> map = personList.stream()
  .collect(groupingBy(Person::getFirstName, groupingBy(Person::getLastName)));

The double grouping gives you a map of a map. That's the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM