微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Java8

如何解决在 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 举报,一经查实,本站将立刻删除。