[英]How can I use groupingBy to return a List<String, String>
I have a List of GroupUser
instances with String getGroup()
and String getName()
methods. 我有一个使用String getGroup()
和String getName()
方法的GroupUser
实例列表。 I want to return a Map<String, List<String>>
where the key is the group and the value is the list of names for that group. 我想返回一个Map<String, List<String>>
,其中键是组,值是该组的名称列表。
If I use 如果我用
Map<String, List<GroupUser>> groupUserList = users.stream()
.collect(Collectors.groupingBy(GroupUser::getGroup));
that returns Map<String, List<GroupUser>>
返回Map<String, List<GroupUser>>
How can I get a Map<String, List<String>>
directly 如何直接获取Map<String, List<String>>
You can get a Map<String, List<String>>
where the key is the group and the value is a list of names with: 您可以获得Map<String, List<String>>
,其中键是组,值是名称列表,具有:
Map<String, List<String>> groupUserList = users.stream()
.collect(
Collectors.groupingBy(GroupUser::getGroup,
Collectors.mapping(GroupUser::getName,
Collectors.toList())));
Explaination: 说明:
Looking at groupingBy javadocs we see that 1 of the overloads has the signature: 通过分组查看javadocs,我们看到其中1个重载具有签名:
public static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
You can think of this downstream
as a collector that tells the stream what to do with the elements that it separated by key (in our case the group is the key). 您可以将其视为downstream
的收集器,该收集器告诉流如何处理由键分隔的元素(在本例中,组是键)。
Notice that it is another collector . 请注意,它是另一个收集器 。 Next we want to transform a GroupUser
into a String
which is it's name. 接下来,我们要将GroupUser
转换为String
,即其名称。 We know we transform elements of a stream with map
. 我们知道我们使用map
转换流的元素。 However this takes a Collector
. 但是,这需要一个Collector
。
Look further into the Collectors API we see that we already have a collector that maps elements and takes another Collector
进一步查看Collectors API,我们看到我们已经有一个收集器,该收集器映射元素并采用另一个Collector
public static <T,U,A,R> Collector<T,?,R> mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
Now from the docs: downstream - a collector which will accept mapped values
. 现在从docs: downstream - a collector which will accept mapped values
。 Since we mapped GroupedUser
to it's name the last thing left to do is to collect them in a list and that is one of the most commonly used collectors. 因为我们将GroupedUser
映射到它的名称,所以剩下要做的最后一件事就是将它们收集在一个列表中,这是最常用的收集器之一。 Collectors.toList()
Bottom line: Simple usage of collectors tells you that this is where you finished the processing of your stream, however we can compose collectors in more complex scenarios like this one. 底线:收集器的简单用法告诉您,这是您完成流处理的地方,但是我们可以在像这样的更复杂的场景中组成收集器 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.