我有一个Stream<Pair<String, String>> myStream;
,我想将其汇总到Map<String, Set<String>> result;
我设法做到以下几点:
Map<String, Set<Pair<String, String>>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Collectors.toSet()));
此操作失败,并显示“无法从静态contex引用非静态方法”:
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Pair::getValue, Collectors.toSet()));
我在做什么错了?
答案 0 :(得分:7)
正确的代码是:
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey,
Collectors.mapping(Pair::getValue, Collectors.toSet())));
如果您使用import static
,则将其缩短为:
Map<String, Set<String>> result = myStream
.collect(groupingBy(Pair::getKey, mapping(Pair::getValue, toSet())));