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
The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Set<Object>>)
"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?
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());
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