Java,Lambda:如何从具有多个不同类型列表的 Class 中选择一个列表?

Java, Lambda: How to pick a List from a Class with several Lists of different Types?

在 Java 8 中,从对象列表(记录)中挑选和收集 Lists<T> 的最佳方法是什么,该列表包含多个不同类型的列表 {List<Type1>, List<Type2>, List<Type3>, ..}

Type1、Type2、Type3 等彼此不相关。 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? 
}

我相信通过一个 getter Function returns 所需的 List 可以工作:

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]