简体   繁体   English

如何使用Java Stream map在不同类型之间进行映射?

[英]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 但它不会起作用: 不兼容的类型:lambda表达式中的错误返回类型

Arrays.stream with an int[] will give you an IntStream so map will expect a IntUnaryOperator (a function int -> int ). 带有int[] Arrays.stream将为您提供一个IntStream因此map将需要一个IntUnaryOperator (函数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). 你提供的函数是int -> T类型,其中T是一个对象(如果由于取消装箱而T是一个Integer ,它将起作用,但对于无界泛型类型参数,假设它是泛型类型则不起作用)。

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> : 您正在寻找的是使用mapToObj ,它需要一个IntFunction (一个函数int -> T )并返回一个Stream<T>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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