Java stream - map and store array of int into Set
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());
Arrays.stream(int[])
returns an IntStream
. And IntStream
does not offer collect()
methods that take a Collector
.
If you need to use Collectors.toSet()
, then you need a Stream<Integer>
for it, and you can call mapToObj
for that:
Set<Integer> mySet = Arrays.stream(arr1)
.mapToObj(ele -> ele - 2)
.collect(Collectors.toSet());