Java: groupingBy subvalue as value

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.


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())));