Java:groupingBy subvalue as value

Phi*_*hil 8 java java-stream collectors

比方说,我有一个对象Person,其字段类型为FirstName和LastName.现在我也有一个List<Person>,我喜欢使用流.

现在我想生成一个Map<FirstName, List<LastName>>以便将具有相同名字的人分组.如何在不编写大量代码的情况下解决这个问题?到目前为止我的方法是

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

但似乎这是分配地图价值的错误方法.我应该改变什么?或者我应该使用.reduce new HashMap<FirstName, List<LastName>>()作为初始值,然后通过将元素放入其中来聚合它?

Eug*_*ene 10

personList.stream()
          .collect(Collectors.groupingBy(
               Person::getFirstName,
               Collectors.mapping(Person::getLastName, Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)

您正在寻找下游收集器 groupingBy


Nam*_*man 5

这应该适合你:

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