Dmytrii S.
Dmytrii S.

Reputation: 261

How to use Java Stream map for mapping between different types?

I have two arrays of equal size:

  1. int[] permutation
  2. T[] source

I want to do smth like this

Arrays.stream(permutation).map(i -> source[i]).toArray();

But it won't work saying: Incompatible types: bad return type in lambda expression

Upvotes: 7

Views: 16598

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

Arrays.stream with an int[] will give you an IntStream so map will expect a IntUnaryOperator (a function int -> int).

The function you provide is of the type int -> T where T is an object (it would work if T was an Integer due to unboxing, but not for an unbounded generic type parameter, assuming it's a generic type).

What you are looking for is to use mapToObj instead, which expects an IntFunction (a function int -> T) and gives you back a Stream<T>:

//you might want to use the overloaded toArray() method also.
Arrays.stream(permutation).mapToObj(i -> source[i]).toArray();

Upvotes: 17

Related Questions