How do you use flatMap() to flatten nested lists in Java streams?

flatMap() is an intermediate Stream operation that transforms each element into its own stream and then merges all those streams into a single, flattened stream.

Key Points

Example

Given a list of lists like [[1, 2], [3, 4, 5]], flatMap(List::stream) merges them into one flat stream containing 1, 2, 3, 4, 5.

List<List<Integer>> nestedNumbers = Arrays.asList(
        Arrays.asList(1, 2), Arrays.asList(3, 4, 5));

List<Integer> flatList = nestedNumbers.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

Interview Tip

A concise interview answer is

flatMap() converts each element into its own stream and merges all of them into one flattened stream, which is exactly what I need for a List<List<Integer>> - flatMap(List::stream) turns the nested lists into a single flat stream of integers, unlike map(), which would leave it nested.

Last updated: 11 November 2026

Previous question: How does findFirst() work in Java streams?

Next question: How do you group elements using Java streams?

More Stream API Coding Questions - Level I interview questions

All Stream API Coding Questions - Level I questions