简体   繁体   English

要映射的Java 8 int数组

[英]Java 8 int array to map

I want to convert int array to 我想将int数组转换为

Map<Integer,Integer> 

using Java 8 stream api 使用Java 8 stream api

int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
                .stream(nums)
                .collect(Collectors.toMap(e->e,1));

I want to get a map like below, key will be integer value, value will be total count of each key 我想得到一个如下图,键将是整数值,值将是每个键的总数

map={2->3, 7->1, 11->2, 15->1} map = {2-> 3,7-> 1,11-> 2,15-> 1}

compiler complains " no instance(s) of type variable(s) T, U exist so that Integer confirms to Function " 编译器抱怨“ 没有类型变量的实例(T),U存在,因此Integer确认函数

appreciate any pointers to resolve this 感谢任何指针来解决这个问题

You need to box the IntStream and then use groupingBy value to get the count: 您需要IntStream ,然后使用groupingBy值来获取计数:

Map<Integer, Long> map = Arrays
        .stream(nums)
        .boxed() // this
        .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

or use reduce as: 或使用reduce作为:

Map<Integer, Integer> map = Arrays
        .stream(nums)
        .boxed()
        .collect(Collectors.groupingBy(e -> e,
                Collectors.reducing(0, e -> 1, Integer::sum)));

You have to call .boxed() on your Stream to convert the IntStream to a Stream<Integer> . 您必须在Stream上调用.boxed()以将IntStream转换为Stream<Integer> Then you can use Collectors.groupingby() and Collectors.summingInt() to count the values: 然后,您可以使用Collectors.groupingby()Collectors.summingInt()来计算值:

Map<Integer, Integer> map = Arrays.stream(nums).boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(i -> 1)));

You can also accomplish counting the ints without boxing the int values into a Map<Integer, Integer> or Map<Integer, Long> . 您还可以完成对int的计数,而无需将int值装入Map<Integer, Integer>Map<Integer, Long> If you use Eclipse Collections , you can convert an IntStream to an IntBag as follows. 如果使用Eclipse Collections ,则可以将IntStream转换为IntBag ,如下所示。

int[] nums = {2, 7, 11, 15, 2, 11, 2};
IntBag bag = IntBags.mutable.withAll(IntStream.of(nums));
System.out.println(bag.toStringOfItemToCount());

Outputs: 输出:

{2=3, 7=1, 11=2, 15=1}

You can also construct the IntBag directly from the int array. 您还可以直接从int数组构造IntBag

IntBag bag = IntBags.mutable.with(nums);

Note: I am a committer for Eclipse Collections. 注意:我是Eclipse Collections的提交者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM