0

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.

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
LearningToCode
  • 392
  • 5
  • 18
  • Nested `for`-loops could be used perfectly well for generating [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product), as described in [this currently associated question](https://stackoverflow.com/questions/41653798/convert-classic-nested-for-loop-with-java-8-streams). But the question listed above has nothing to do with Cartesian product. – Alexander Ivanchenko Oct 17 '22 at 20:45

1 Answers1

3

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());
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46