Drex
Drex

Reputation: 3821

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?

Upvotes: 9

Views: 1979

Answers (3)

Donald Raab
Donald Raab

Reputation: 6686

If you're open to using a third-party library, you can avoid boxing the int values as Integer using Eclipse Collections IntSet.

int[] array = {5, 6, 7, 3, 9};
IntStream stream = Arrays.stream(array).map(value -> value - 2);
IntSet actual = IntSets.mutable.ofAll(stream);
IntSet expected = IntSets.mutable.of(3, 4, 5, 1, 7);
Assert.assertEquals(expected, actual);

Note: I am a committer for Eclipse Collections.

Upvotes: 0

ernest_k
ernest_k

Reputation: 45309

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

Upvotes: 7

Eran
Eran

Reputation: 393781

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

Upvotes: 12

Related Questions