I believe passing a getter Function that returns the required List can work:
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());
}
And then you call it with:
List<Type1> getAllOccurrencesForType (Records::getListOfType1,allRecords);
Here's a full example:
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;
}
}
Some main method:
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);
output:
[a, b, c, d]
[1, 2, 4, 3]
[1.1, 4.4, -3.3, 135.3]
@luk2302,@GhostCat: Thanks for your hint. I will check this ASAP. I asked a colleague of mine yesterday to try to find a solution for this task and he worked on my PC, while I was in meeting. I assume he used my account to post the same question. If so, I will flag this one as duplicated. Thanks again!