2017-07-17 2 views
0

私は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()); 
+0

はない '.MAPい(B - >() - > b)の'の仕事を? – Eran

+0

いいえ、私はこれを試して、エラーが発生しました: ラムダ変換のターゲットタイプは、あなたが 'mapToSomethingElseWith()'を呼び出すインターフェイス – Ste

+0

でなければならないが、 'mapToSomethingElseWith()'と宣言されている – davidxxx

答えて

1

:次に

public static B mapFrom(A a){...} 

どのように最後の2つのmap Sを組み合わせることについて

2

、あなたはチェーンStream<B>

.map(SimpleTest::mapSomethingElseWith); 

mapToSomethingElseWith()mapToSomethingElseWith(Supplier<B> b)として定義されます。

ので、コンパイラは、引数としてSupplier<B>なくBmapToSomethingElseWith()方法を持っていることを期待しかし、あなたはにB変数を渡します。

問題を解決する方法は、map()メソッドを使用して、mapToSomethingElseWith()Supplier<B>を呼び出す明示的なラムダを使用しています。 bはラムダのタイプBの引数がSupplier<B>である

()-> b。 実際には引数はなく、Bインスタンスを返します。

あなたがそう書くことができます。

map(SimpleTest::mapSomethingElseWith); 
    List<Integer> l = a.stream() 
    .map(B::mapFrom)   
    .map(b->SimpleTest.mapToSomethingElseWith(()-> b)) 
    .collect(Collectors.toList()); 
関連する問題