我该如何计算groupBy的出现次数? [英] How can I count occurrences with groupBy?

查看:226
本文介绍了我该如何计算groupBy的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将流中的项目收集到一个映射中,该映射将相等的对象分组在一起,并映射到出现的次数.

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

我该怎么办?

推荐答案

我认为您只是在寻找

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的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆