Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refactoring a nested loop into Java 8 streams collecting the outer objects

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 Java8 streams and I came up with this solution I’m stuck with because it collects objects of type B instead of AList<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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


I found many results here in SO looking for [java] nested foreach stream but I couldn’t find anything that suits my needs.

>Solution :

You don’t need flatMap here. Just apply a filter on the Stream<A>.

List<A> results = 
    listOfA.stream()
           .filter(a -> a.getListOfB()
                         .stream()
                         .anyMatch(b -> "myString".equals(b.getMyString())))
           .collect(Collectors.toList());

This is assuming you don’t want to add an instance of A multiple times to the List if it has multiple B instances that match "myString".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading