I have a loop which does what I want - it adds objects of type A to the results list:
ArrayList<A> results = new ArrayList<>();
for (A a: listOfA) {
for (B b : a.getListOfB()) {
if ("myString".equals(b.getMyString())) {
results.add(a);
}
}
}
Now I'd like to refactor my code using Java 8 streams and I came up with this solution I'm stuck with because it collects objects of type B instead of A - List<A> results = ... is obviously wrong:
List<A> results = listOfA.stream()
.flatMap(a -> a.getListOfB().stream())
.filter(b -> "myString".equals(b.getMyString()))
.collect(Collectors.toList());
How can I collect a list of type A using Java 8 streams?
I found many results here in SO looking for [java] nested foreach stream but I couldn't find anything that suits my needs.