[英]How to group a stream to a map by using a specific key and value?
I have a Stream<Pair<String, String>> myStream;
我有一个Stream<Pair<String, String>> myStream;
and I'd like to aggregate it into a Map<String, Set<String>> result;
我想将它聚合成Map<String, Set<String>> result;
I managed to get to the following: 我设法达到以下目的:
Map<String, Set<Pair<String, String>>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Collectors.toSet()));
This fails with "Non-static method cannot be referenced from a static contex": 这失败了“无法从静态上下文引用非静态方法”:
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Pair::getValue, Collectors.toSet()));
What am I doing wrong? 我究竟做错了什么?
Correct code is: 正确的代码是:
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey,
Collectors.mapping(Pair::getValue, Collectors.toSet())));
If you use import static
, it is shortened to: 如果使用import static
,则缩写为:
Map<String, Set<String>> result = myStream
.collect(groupingBy(Pair::getKey, mapping(Pair::getValue, toSet())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.