在 Java8

问题描述

我有一个整数输入数组,我想获取数组中元素出现的次数。 例如,input[]={0,1,2,1} 应该输出一个整数映射,例如 {0=1,1=3,2=1}

如何计算出现次数并将其添加到 Java 8 流中的映射?

我尝试了以下操作,但出现编译问题:

Map<Integer,Long> count = Arrays.stream(nums)
        .collect(Collectors.groupingBy(
                i -> i,Collectors.counting())
        );

我得到的错误是这样的:

    Unresolved compilation problems: 
    The method collect(supplier<R>,ObjIntConsumer<R>,BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Map<Object,Long>>)
    Type mismatch: cannot convert from Collector<Object,capture#10-of ?,Long>> to supplier<R>

在 Stackoverflow 解决方案中,建议使用 Boxed() 如下:

    int[] arr = {1,6,8,5,4,7,7};
    Map<Object,Long> occurrences=Arrays.stream(arr)
        .Boxed()
        .collect(Collectors.groupingBy(s -> s,Collectors.counting()));

但是如果希望 MapMap<Integer,Long> or Map<Integer,Integer> 类型,那么我该如何实现?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)