私は必要な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]
あなたのコードがあり、各タイプの1つの出現が正確であり、あなたがrecord.getListOfType1()を使用することができるということのようである場合。おそらく、これらのリストをレコードクラスに動的に追加するのでしょうか? –
https://stackoverflow.com/questions/46894007/java-lambda-how-to-find-a-list-from-a-collection-of-lists-with-different-typesとの違いは何ですか? – luk2302
私は@ luk2302に同意します - あなたは同じことをもう一度求めているようです。たぶん私は間違っています - しかし、なぜこの第二の質問が必要なのか、あなたが以前に尋ねた質問とはどこが違うのか説明してください。 – GhostCat