4

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
  • 3
    Arrays.stream(nums).boxed().collect(Collectors.toMap(Function.identity(), i -> 1, Integer::sum)); Commented Jun 1, 2019 at 12:21

3 Answers 3

8

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)));
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer, if the map value is just 1 instead of key count, is it possible to use Collectors.toMap(e->e,1), by modifying it
@Buddhi, No, should be ...Collectors.toMap(e->e,v->1)...
@HadiJ but you’d need Collectors.toMap(e->e, v->1, Integer::sum) in this specific case, to handle the duplicates.
@Holger, yeah, I meant for this ...toMap(e->e,1). thanks for clearing
4

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)));

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.