How do I use Java Stream Map to map between different types?

I have two arrays of the same size:

  • int[] permutation

  • T[] source

I want to do something like this

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

      

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

+3


source to share


1 answer


Arrays.stream

c int[]

will give you IntStream

, so map

expect a IntUnaryOperator

(function int -> int

).

The function you provide is of type int -> T

where T is an object (it would work if it T

was Integer

due to unboxing, but not for an unbounded type parameter, assuming it's a generic type).



Instead, you should use mapToObj

, which expects IntFunction

(function int -> T

) and returns to you Stream<T>

:

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

      

+10


source







All Articles