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.
>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());