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.


Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org










Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap