简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM