Java:将子值作为值分组 [英] Java: groupingBy subvalue as value
问题描述
比方说,我有一个对象Person,其字段类型为FirstName和LastName.现在,我还有一个 List< Person>
,并且我喜欢使用流.
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.
现在,我想生成一个 Map< FirstName,List< LastName>>
以便对具有相同名字的人进行分组.如何在不编写大量代码的情况下进行此操作?到目前为止,我的方法是
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
));
,但是这似乎是分配地图值的错误方法.我应该改变什么?还是我应该将.reduce与 new HashMap< FirstName,List< LastName>>>()
用作初始值,然后通过将元素放入其中来汇总到它?
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())));
您正在寻找具有 groupingBy
这篇关于Java:将子值作为值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!