Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream - map and store array of int into Set

I have an array of [5, 6, 7, 3, 9], I would like to change each element from the array substracting by 2, then store the in a Set, so what I did is

Set<Integer> mySet = Arrays.stream(arr1).map(ele -> new Integer(ele - 2)).collect(Collectors.toSet());

but I am getting two exceptions here as

  1. The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Set<Object>>)"
  2. Type mismatch: cannot convert from Collector<Object,capture#1-of ?,Set<Object>> to Supplier<R>

What does those error mean and how can I fix the issue here with Java Stream operation?

like image 444
Kev D. Avatar asked Apr 27 '20 06:04

Kev D.


1 Answers

It looks like arr1 is an int[] and therefore, Arrays.stream(arr1) returns an IntStream. You can't apply .collect(Collectors.toSet()) on an IntStream.

You can box it to a Stream<Integer>:

Set<Integer> mySet = Arrays.stream(arr1)
                           .boxed()
                           .map(ele -> ele - 2)
                           .collect(Collectors.toSet());

or even simpler:

Set<Integer> mySet = Arrays.stream(arr1)
                           .mapToObj(ele -> ele - 2)
                           .collect(Collectors.toSet());
like image 149
Eran Avatar answered Sep 19 '22 04:09

Eran