如何使用 groupBy 计算出现次数? [英] How can I count occurrences with groupBy?

查看:67
本文介绍了如何使用 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

我该怎么做?

推荐答案

我认为您只是在寻找 overload 需要另一个 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 计算出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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