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
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With