Java计数整数数组中每个元素的出现次数 [英] Java count occurrence of each element in an integer array

查看:1651
本文介绍了Java计数整数数组中每个元素的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码段来计算每个元素的出现次数。是否有可能以更短的方式实现这一目标?

I've written the following snippet to count the number of occurrences of each element. Is it possible to achieve this in a much shorter way?

int[] arr = {1, 6, 2, 8, 5, 4, 7, 7, 5, 7};
Arrays.stream(arr)
        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
        .stream()
        .collect(Collectors.groupingBy(s -> s))
        .forEach((k, v) -> System.out.println(k+" "+v.size()));

此外,我想只显示超过1次的元素。所以我尝试修改如下导致错误。

Also I would like to display only the elements which occur more than 1 time. So I tried modifying as below which resulted in an error.

.forEach((k, v) -> if(v.size() > 1) System.out.println(k+" "+v.size()));

这样做的正确方法是什么?

What is the correct way to do this?

推荐答案

对于后一个问题,你必须改变

For the latter question, you have to change

.forEach((k, v) -> if(v.size() > 1) System.out.println(k+" "+v.size()));

.forEach((k, v) -> {if(v.size() > 1) System.out.println(k+" "+v.size());});

对于第一部分,目前尚不清楚为什么需要第一个 collect 后跟第二个 Stream 管道。
如果目的是将 IntStream 转换为 Stream< Integer> ,请使用 boxed()

For the first part, it's not clear why you need the first collect followed by a second Stream pipeline. If the purpose was to convert an IntStream to a Stream<Integer>, use boxed():

Arrays.stream(arr)
      .boxed()
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

正如Dici建议的那样,你也可以链接收藏家将每个数字与其出现次数分组:

As Dici suggested, you can also chain Collectors to group each number with its number of occurrences :

Map<Integer,Integer> occurrences = 
    Arrays.stream(arr)
          .boxed()
          .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

这篇关于Java计数整数数组中每个元素的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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