Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 537
Dmytrii S. Avatar asked Jul 30 '15 10:07

Dmytrii S.


1 Answers

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();
like image 170
Alexis C. Avatar answered Oct 02 '22 20:10

Alexis C.