Is Stream within a Stream Possible in Java?


It is not possible to have a Stream within a Stream (nested Streams) in Java.

But! You can achieve the same functionality of nested streams using map() and flatMap() methods.

Example:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NestedStreamExample {

    public static void main(String[] args) {

        List<List<String>> nestedList = Arrays.asList(
                Arrays.asList("A", "B", "C","D"),
                Arrays.asList("E", "F","H","I")
        );

        List<String> flattenedList = nestedList.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());

        System.out.println(flattenedList);
    }
}

[A, B, C, D, E, F, H, I]


We here have a nested list of Strings. When we use the flatMap() along with List::stream we are flattening the nested structure.

Note that the inner stream() call converts each inner list into a stream, and flatMap() combines these streams into a single stream of Strings.


-




Have Questions? Post them here!