2017-10-24 7 views
-1

&を選択するJava 8の最良の方法は、異なるタイプの複数のリストを持つオブジェクト(レコード)のリストLists<T>を収集{List<Type1>, List<Type2>, List<Type3>, ..}Java、Lambda:異なるタイプの複数のリストを持つクラスからリストを選択するにはどうすればよいですか?

タイプ1、タイプ2、タイプ3などは互いに関係しません。 T =タイプ1、タイプ2、タイプ3 ...

List<Records> allRecords; 

class Records { 
    List<Type1> listOfType1; // can be empty or null 
    List<Type2> listOfType2; // can be empty or null 
    List<Type3> listOfType3; // can be empty or null 
} 

List<T> getAllOccurrencesForType(T t, List<Records> allRecords) { 
    return ?all occurrences of List<t> from all Records collected to one List? 
} 
+0

あなたのコードがあり、各タイプの1つの出現が正確であり、あなたがrecord.getListOfType1()を使用することができるということのようである場合。おそらく、これらのリストをレコードクラスに動的に追加するのでしょうか? –

+5

https://stackoverflow.com/questions/46894007/java-lambda-how-to-find-a-list-from-a-collection-of-lists-with-different-typesとの違いは何ですか? – luk2302

+0

私は@ luk2302に同意します - あなたは同じことをもう一度求めているようです。たぶん私は間違っています - しかし、なぜこの第二の質問が必要なのか、あなたが以前に尋ねた質問とはどこが違うのか説明してください。 – GhostCat

答えて

1

私は必要なListが動作することができます返すゲッターFunction渡し信じる:

static <T> List<T> getAllOccurrencesForType(Function<Records,List<T>> getter, List<Records> allRecords) { 
    return allRecords.stream() 
        .flatMap(r->getter.apply(r).stream()) 
        .collect(Collectors.toList()); 
} 

をそしてあなたがそれを呼び出す:

List<Type1> getAllOccurrencesForType (Records::getListOfType1,allRecords); 

完全な例は次のとおりです。

class Records { 
    List<String> listOfType1; 
    List<Integer> listOfType2; 
    List<Double> listOfType3; 
    public Records (List<String> l1, List<Integer> l2, List<Double> l3) { 
     listOfType1 = l1; 
     listOfType2 = l2; 
     listOfType3 = l3; 
    } 
    public List<String> getListOfType1() { 
     return listOfType1; 
    } 
    public List<Integer> getListOfType2(){ 
     return listOfType2; 
    } 
    public List<Double> getListOfType3(){ 
     return listOfType3; 
    } 
} 

一部main方法:

List<Records> recs = new ArrayList<>(); 
recs.add (new Records (Arrays.asList ("a","b"), Arrays.asList (1,2), Arrays.asList (1.1,4.4))); 
recs.add (new Records (Arrays.asList ("c","d"), Arrays.asList (4,3), Arrays.asList (-3.3,135.3))); 
List<String> allStrings = getAllOccurrencesForType(Records::getListOfType1,recs); 
List<Integer> allIntegers = getAllOccurrencesForType(Records::getListOfType2,recs); 
List<Double> allDoubles = getAllOccurrencesForType(Records::getListOfType3,recs); 
System.out.println (allStrings); 
System.out.println (allIntegers); 
System.out.println (allDoubles); 

出力:

[a, b, c, d] 
[1, 2, 4, 3] 
[1.1, 4.4, -3.3, 135.3] 
+0

こんにちはEran、ありがとう、ありがとう:-) 'getAllOccurrencesForType()'メソッドから 'r-> getter.apply(r)'のために次のコンパイルエラーが発生します! 'の型引数を推論できませんflatMap(Function <?super T ,? extends Stream >)' – ThomasMuller

+0

@ThomasMuller投稿したコードは、コンパイルをパスしてEclipse Neonで実行されます。どのIDEを使用していますか? – Eran

+0

Eran、私はWeb開発者向けにOxygen、Java EE IDEを使用しています – ThomasMuller

関連する問題