Java 8: Flatten nested collections with flatMap

flatMap turns a stream of collections into one flat stream of elements.

Code
List<List<Integer>> nested = List.of(
        List.of(1, 2), List.of(3), List.of(4, 5));
List<Integer> flat = nested.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());
System.out.println(flat);
Output
[1, 2, 3, 4, 5]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26