问题描述
我想将流中的项目收集到一个映射中,该映射将相等的对象分组在一起,并映射到出现的次数.
I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.
List<String> list = Arrays.asList("Hello", "Hello", "World");
Map<String, Long> wordToFrequency = // what goes here?
因此,在这种情况下,我希望地图包含以下条目:
So in this case, I would like the map to consist of these entries:
Hello -> 2
World -> 1
我该怎么办?
推荐答案
我认为您只是在寻找重载,这需要另一个Collector
来指定要执行的操作每个组...然后按Collectors.counting()
进行计数:
I think you're just looking for the overload which takes another Collector
to specify what to do with each group... and then Collectors.counting()
to do the counting:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted);
}
}
结果:
{Hello=2, World=1}
(也有可能使用groupingByConcurrent
来提高效率.如果在您的上下文中安全的话,请记住您的真实代码.)
(There's also the possibility of using groupingByConcurrent
for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)
这篇关于我该如何计算groupBy的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!