Java 8 int array to map

拟墨画扇 提交于 2020-07-18 06:07:09

问题


I want to convert int array to

Map<Integer,Integer> 

using 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}

compiler complains "no instance(s) of type variable(s) T, U exist so that Integer confirms to Function"

appreciate any pointers to resolve this


回答1:


You need to box the IntStream and then use groupingBy value to get the count:

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

or use reduce as:

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



回答2:


You have to call .boxed() on your Stream to convert the IntStream to a Stream<Integer>. Then you can use Collectors.groupingby() and Collectors.summingInt() to count the values:

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



回答3:


You can also accomplish counting the ints without boxing the int values into a Map<Integer, Integer> or Map<Integer, Long>. If you use Eclipse Collections, you can convert an IntStream to an IntBag as follows.

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.

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

Note: I am a committer for Eclipse Collections.



来源:https://stackoverflow.com/questions/56406621/java-8-int-array-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!