flatMap: Flattening Nested Data

Streams · lesson 5 of 42 · 3 min read

Turn nested collections into one flat stream, and expand one element into many.

Open this lesson in the learning hub

Key points

  • map over a list of lists leaves you holding a stream of lists. Still nested.
  • flatMap wants a Stream back for each element, then pours them all into one flat stream.
  • One element can produce many results, one, or none. Return Stream.empty() to drop it.
  • Reach for it on one-to-many shapes: orders to line items, sentences to words, parents to children.
  • Primitive variants exist too: flatMapToInt and friends. mapMulti (Java 16+) avoids a Stream per element when speed matters.

Example

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<List<String>> teams = List.of(
                List.of("ada", "alan"),
                List.of("grace"),
                List.of());

        // map leaves you holding a stream of lists -- still nested.
        System.out.println("map     : " + teams.stream().map(t -> t).toList());

        // flatMap opens each inner stream and pours it into one flat stream.
        System.out.println("flatMap : " + teams.stream().flatMap(List::stream).toList());

        // Classic use: one sentence in, many words out.
        System.out.println("words   : " + Stream.of("hello there", "streams are flat")
                .flatMap(s -> Arrays.stream(s.split(" ")))
                .toList());

        // Each element may produce zero, one, or many results.
        System.out.println("expand  : " + Stream.of(1, 2, 3, 4)
                .flatMap(n -> n % 2 == 0 ? Stream.of(n, n) : Stream.empty())
                .toList());
    }
}

flatMap is map plus flatten, in a single pass.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.