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.

import java.util.Arrays;
import java.util.List;

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 =


[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!