私はjava8からのストリームAPIを使用して、オブジェクトを別のオブジェクトにマップし、このオブジェクトをサプライヤを予期するメソッドに渡すと、コンパイルエラーが発生します。このオブジェクトをメソッドに渡すにはどうすればよいですか?より良い説明のためにインスタンスからサプライヤを取得する方法は?
が、私はコードを次のように書いた:
public class SimpleTest {
public static class B{
public static B mapFrom(A a){
return new B(); //transform to b
}
}
public static class A{
}
public static Integer mapToSomethingElseWith(Supplier<B> b){
return 1;
}
public static void example(){
List<A> a = Lists.newArrayList(new A(),new A(),new A());
List<Integer> l = a.stream()
.map(B::mapFrom)
.map(SimpleTest::mapSomethingElseWith); //does not work. Bad return type in method reference: cannot convert java.lang.Integer to R
.collect(Collectors.toList());
}
}
私の現在の(醜い)ソリューションは、次のようになります。
List<Integer> l = a.stream()
.map(B::mapFrom)
.map((b)-> ((Supplier)() -> b) // map to supplier
.map(SimpleTest::mapSomethingElseWith)
.collect(Collectors.toList());
は似ていますが、より表現の何かが存在しますか? B
を返し
List<Integer> l = a.stream()
.map(B::mapFrom)
あなたはmapFrom()
方法としてStream<B>
を取得する:あなたが書くとき
List<Integer> l = a.stream()
.map(B::mapFrom)
.map(b -> SimpleTest.mapSomethingElse (() -> b))
.collect(Collectors.toList());
はない '.MAPい(B - >() - > b)の'の仕事を? – Eran
いいえ、私はこれを試して、エラーが発生しました: ラムダ変換のターゲットタイプは、あなたが 'mapToSomethingElseWith()'を呼び出すインターフェイス – Ste
でなければならないが、 'mapToSomethingElseWith()'と宣言されている – davidxxx