Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 int array to map

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

like image 746
Buddhi Avatar asked Dec 11 '22 02:12

Buddhi


1 Answers

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)));
like image 118
Naman Avatar answered Dec 30 '22 08:12

Naman