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

Simplify the following 2 for-loop using java streams

I am trying to achieve the following by converting two for loops using Java Streams.

    Set<Type2> set = new HashSet<>();
    for (Test1 test1 : testlist1){ // testlist1 is a list
      for (Test2 test2 : test1.getList()){ // test1.getList returns a list
        set.add(test2);
      }
    }

New to Java streams and trying to convert it.

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

>Solution :

You can use Stream.flatMap() to achieve the same result:

Set<Type2> set = testlist1.stream()             // Stream<Type1>
    .flatMap(test1 -> test1.getList().stream()) // Stream<Type2>
    .collect(Collectors.toSet());

Another option is to use Java 16 Stream.mapMulti(), which would be more performant than flatMap() in case if lists returned by test1.getList() would contain only a few elements or even can be empty.

Set<Type2> set = testlist1.stream()
    .<Type2>mapMulti((test1, c) -> test1.getList().forEach(c))
    .collect(Collectors.toSet());
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