flatMap

map turns each element into exactly one result; flatMap turns each element into a stream of any number of results and joins those streams into one. That makes it the tool for flattening nested lists, splitting text, dropping empty Optionals and generating combinations. This page explains how flatMap works, runs the common patterns, covers flatMapping and mapMulti, and compares it with loops.

Contents

What flatMap does

map is a one-to-one transformation: each element becomes exactly one new element. A stream of orders mapped to their item lists therefore becomes a stream of lists. flatMap is one-to-many: the function returns a stream for each element, which may have zero, one or many elements. flatMap then concatenates all of those streams into one flat stream.

The inner streams are consumed one after another, lazily, as the outer stream is pulled. Nothing is collected in between, and an element that maps to an empty stream simply disappears from the result.

The flatMap family
MethodSinceBest for
Stream.flatMapJava 8Flattening nested collections; one-to-many mappings
flatMapToInt, flatMapToLong, flatMapToDoubleJava 8Flattening into primitive streams without boxing
Optional.flatMapJava 8Chaining lookups that each return an Optional
Optional.streamJava 9Dropping empty results in a stream
Collectors.flatMappingJava 9Flattening inside groupingBy or partitioningBy
Stream.mapMultiJava 16One-to-many without creating a stream per element

Every program on this page ran on JDK 21. Streams in general are introduced on the streams page.

map versus flatMap

Each order holds a list of items, one order is empty, and one item appears in two orders, so the difference between the two methods, and what to do afterwards, is easy to see.

Java
import java.util.List;

public class MapVsFlatMap {

    record Order(int id, List<String> items) {
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order(1, List.of("pen", "ink")),
                new Order(2, List.of("paper")),
                new Order(3, List.of()),
                new Order(4, List.of("pen", "stapler")));

        // map: one result per order, so you get a list of lists
        List<List<String>> nested = orders.stream().map(Order::items).toList();
        System.out.println("map:              " + nested);

        // flatMap: each order gives a stream; the streams are joined end to end
        List<String> flat = orders.stream().flatMap(o -> o.items().stream()).toList();
        System.out.println("flatMap:          " + flat);

        // Typical follow-up: distinct, counted or sorted across all orders
        System.out.println("distinct sorted:  " + flat.stream().distinct().sorted().toList());
        int total = orders.stream().mapToInt(o -> o.items().size()).sum();
        System.out.println("total items:      " + total);
    }
}

Output:

Output
map:              [[pen, ink], [paper], [], [pen, stapler]]
flatMap:          [pen, ink, paper, pen, stapler]
distinct sorted:  [ink, paper, pen, stapler]
total items:      5
  • map(Order::items) gave a list of four lists, including the empty one: the nesting is kept.
  • flatMap(o -> o.items().stream()) gave one list of five items, and the empty order contributed nothing.
  • After flattening, the usual stream operations apply to the individual items: distinct and sorted removed the duplicate pen, and count totalled all items across orders.

Common patterns

Five short examples cover the situations where flatMap appears most often in real code: text, optional results, maps of lists, combinations and the newer mapMulti.

Java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

public class FlatMapPatterns {

    static Optional<Integer> parse(String s) {
        try {
            return Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    public static void main(String[] args) {
        // 1. Words from lines of text
        List<String> lines = List.of("the quick fox", "jumps over", "the lazy dog");
        List<String> words = lines.stream()
                .flatMap(line -> Arrays.stream(line.split(" ")))
                .toList();
        System.out.println("words:     " + words);

        // 2. Keep only values that parsed: Optional.stream() is empty or one element
        List<Integer> numbers = Stream.of("4", "x", "15", "", "8")
                .map(FlatMapPatterns::parse)
                .flatMap(Optional::stream)
                .toList();
        System.out.println("parsed:    " + numbers);

        // 3. All values of a map of lists
        Map<String, List<String>> teams =
                Map.of("red", List.of("ann", "bo"), "blue", List.of("cy"));
        List<String> members = teams.values().stream().flatMap(List::stream).sorted().toList();
        System.out.println("members:   " + members);

        // 4. Every pair from two lists
        List<String> sizes = List.of("S", "M");
        List<String> colors = List.of("red", "blue");
        List<String> variants = sizes.stream()
                .flatMap(s -> colors.stream().map(c -> s + "-" + c))
                .toList();
        System.out.println("variants:  " + variants);

        // 5. mapMulti (Java 16+): push 0..n results without building a stream
        List<Object> mixed = List.of(1, List.of(2, 3), 4);
        List<Integer> ints = mixed.stream()
                .<Integer>mapMulti((item, sink) -> {
                    if (item instanceof List<?> l) {
                        l.forEach(x -> sink.accept((Integer) x));
                    } else {
                        sink.accept((Integer) item);
                    }
                })
                .toList();
        System.out.println("mapMulti:  " + ints);
    }
}

Output:

Output
words:     [the, quick, fox, jumps, over, the, lazy, dog]
parsed:    [4, 15, 8]
members:   [ann, bo, cy]
variants:  [S-red, S-blue, M-red, M-blue]
mapMulti:  [1, 2, 3, 4]
  • Splitting each line with Arrays.stream(line.split(" ")) and flattening turns a list of lines into a list of words.
  • Parsing each string into an Optional<Integer> and flattening with Optional::stream keeps the numbers that parsed and drops the rest, in one step.
  • teams.values().stream().flatMap(List::stream) collects all members of a map of lists.
  • A nested flatMap over sizes and colours generates every combination, the stream form of two nested loops.
  • mapMulti, from Java 16, passes each element and a sink to a function that calls sink.accept once per result. It avoids creating a small stream for every element, and the type witness <Integer> tells the compiler the result type.

Keeping context, grouping, Optional and primitives

Orders with order lines show patterns that come up once data is nested two levels deep: an order with no lines, and a product that appears in several orders.

Java
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class FlatMapMore {

    record Order(String id, List<Line> lines) {
    }

    record Line(String product, int qty) {
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("o1", List.of(new Line("pen", 2), new Line("ink", 1))),
            new Order("o2", List.of()),
            new Order("o3", List.of(new Line("pen", 5))));

        // Keep context from the outer level: pair each line with its order id
        List<String> rows = orders.stream()
            .flatMap(o -> o.lines().stream().map(l -> o.id() + ":" + l.product()))
            .toList();
        System.out.println("rows:           " + rows);

        // Totals per product across all orders
        Map<String, Integer> totals = orders.stream()
            .flatMap(o -> o.lines().stream())
            .collect(Collectors.groupingBy(Line::product, TreeMap::new,
                Collectors.summingInt(Line::qty)));
        System.out.println("totals:         " + totals);

        // flatMapping as a downstream collector (Java 9)
        Map<Boolean, List<String>> productsByHasLines = orders.stream()
            .collect(Collectors.partitioningBy(o -> o.lines().size() > 1,
                Collectors.flatMapping(o -> o.lines().stream().map(Line::product),
                    Collectors.toList())));
        System.out.println("flatMapping:    " + productsByHasLines);

        // Optional.flatMap avoids Optional<Optional<T>>
        Optional<Order> first = orders.stream().findFirst();
        Optional<String> firstProduct = first.flatMap(o -> o.lines().stream().findFirst())
            .map(Line::product);
        System.out.println("Optional.flatMap: " + firstProduct.orElse("none"));

        // flatMapToInt: one IntStream from many
        int sumOfDigits = Stream.of("123", "45").flatMapToInt(String::chars)
            .map(c -> c - '0').sum();
        System.out.println("flatMapToInt:   " + sumOfDigits);

        // Nested loops as a stream: all pairs i < j
        List<String> pairs = IntStream.rangeClosed(1, 4).boxed()
            .flatMap(i -> IntStream.rangeClosed(i + 1, 4).mapToObj(j -> i + "-" + j))
            .toList();
        System.out.println("pairs:          " + pairs);
    }
}

Output:

Output
rows:           [o1:pen, o1:ink, o3:pen]
totals:         {ink=1, pen=7}
flatMapping:    {false=[pen], true=[pen, ink]}
Optional.flatMap: pen
flatMapToInt:   15
pairs:          [1-2, 1-3, 1-4, 2-3, 2-4, 3-4]
  • After flattening, the outer element is gone. To keep it, build the inner results inside the lambda, where the order is still in scope: each row combines the order ID with a product.
  • Flattening order lines and grouping them by product with summingInt gives totals across all orders: 7 pens.
  • Collectors.flatMapping (Java 9) flattens inside a downstream collector, here listing the products of orders with more than one line separately from the rest.
  • Optional.flatMap chains a lookup that itself returns an Optional, giving Optional<Line> rather than Optional<Optional<Line>>.
  • flatMapToInt(String::chars) turns several strings into one IntStream of characters without boxing, summing the digits 1 to 5 to 15.
  • Pairs i < j come from a flatMap over a range that starts after i, the stream version of a triangular nested loop.

flatMap is lazy

Current JDKs make flatMap pull elements from each inner stream only as they are needed. Older releases consumed every inner stream completely, which broke short-circuiting operations such as limit and findFirst; the fix (JDK-8075939) shipped in JDK 10.0.1 and 11 and was backported to 8u222. The program counts how many inner elements are produced when only three results are needed, and searches an infinite inner stream.

Java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class LazyFlatMap {

    public static void main(String[] args) {
        // Each outer element expands to 1,000 inner elements; we only need the first 3
        AtomicInteger produced = new AtomicInteger();
        var first3 = Stream.of("a", "b", "c")
            .flatMap(s -> Stream.iterate(1, i -> i + 1).limit(1000)
                .peek(i -> produced.incrementAndGet())
                .map(i -> s + i))
            .limit(3)
            .toList();
        System.out.println(first3 + ", inner elements produced: " + produced.get());

        // Even an infinite inner stream works with a short-circuiting operation
        String found = Stream.of(10, 20)
            .flatMap(start -> Stream.iterate(start, i -> i + 1))
            .filter(i -> i % 7 == 0)
            .findFirst()
            .map(String::valueOf)
            .orElse("none");
        System.out.println("first multiple of 7 from an infinite inner stream: " + found);
    }
}

Output:

Output
[a1, a2, a3], inner elements produced: 3
first multiple of 7 from an infinite inner stream: 14
  • Each of the three outer elements could produce 1,000 inner elements, but only 3 were produced in total, because limit(3) stopped the pipeline after the first three.
  • The inner stream from Stream.iterate(start, i -> i + 1) never ends, yet findFirst returned 14 immediately. On a JDK without the fix, the same code never finishes.
  • Laziness also means side effects inside the inner lambdas, such as logging, happen only for the elements actually pulled.

How fast is flattening?

The program flattens 200,000 lists of five integers into one list four ways, keeping the fastest of three runs. It runs everything twice and prints only the second round: in a first version without that warm-up, the nested loops ran first, before the JIT compiler had optimised the shared code, and looked about three times slower than the rest.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class FlatMapSpeed {

    public static void main(String[] args) {
        List<List<Integer>> nested = new ArrayList<>();
        for (int i = 0; i < 200000; i++) {
            nested.add(List.of(i, i + 1, i + 2, i + 3, i + 4));
        }
        System.out.println("flatten 200,000 lists of 5 into one list (second of two rounds)");
        for (int round = 0; round < 2; round++) {
            print = round == 1;
            runAll(nested);
        }
    }

    static boolean print;

    static void runAll(List<List<Integer>> nested) {
        time("nested for loops", nested, n -> {
            List<Integer> out = new ArrayList<>();
            for (List<Integer> inner : n) {
                for (int x : inner) {
                    out.add(x);
                }
            }
            return out;
        });
        time("addAll per list", nested, n -> {
            List<Integer> out = new ArrayList<>();
            n.forEach(out::addAll);
            return out;
        });
        time("flatMap(List::stream)", nested, n -> n.stream().flatMap(List::stream).toList());
        time("mapMulti (Java 16)", nested, n -> n.stream()
            .<Integer>mapMulti((inner, sink) -> inner.forEach(sink)).toList());
    }

    // Best of 3 runs
    static void time(String name, List<List<Integer>> n, Function<List<List<Integer>>,
            List<Integer>> f) {
        long best = Long.MAX_VALUE;
        int size = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            size = f.apply(n).size();
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("  %-24s %6.1f ms  (%,d elements)%n", name, best / 1e6, size);
        }
    }
}

Output (approximate times on a 2-CPU Linux machine with JDK 21):

Output
flatten 200,000 lists of 5 into one list (second of two rounds)
  nested for loops           13.7 ms  (1,000,000 elements)
  addAll per list            15.5 ms  (1,000,000 elements)
  flatMap(List::stream)      19.4 ms  (1,000,000 elements)
  mapMulti (Java 16)         18.1 ms  (1,000,000 elements)
  • All four approaches finished in the same range, tens of milliseconds for a million elements, and which one came first changed from run to run on this shared two-CPU machine. Creating a small stream per inner list is cheap.
  • addAll per list grows the target in many steps, and nested loops add one element at a time; neither had a consistent advantage.
  • mapMulti avoids the per-element stream, which matters most for mappings that produce zero or one result, or that would otherwise build a temporary collection.

Pick the version that reads best. For millions of tiny inner collections a loop can still win, but measure before rewriting.

Edge cases: null streams, closing, reuse and recursion

The Stream.flatMap documentation makes a few promises that are easy to overlook, and some mistakes only show up at run time. The program runs five of them on small inputs.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

public class FlatMapTraps {

    record Node(String name, List<Node> children) {
        Stream<Node> flatten() {           // recursive flatMap walks a whole tree
            return Stream.concat(Stream.of(this), children.stream().flatMap(Node::flatten));
        }
    }

    public static void main(String[] args) {
        // 1. A mapper that returns null is treated as an empty stream
        Map<String, List<String>> tags = Map.of("a", List.of("x", "y"));
        List<String> found = Stream.of("a", "b")
            .flatMap(k -> tags.containsKey(k) ? tags.get(k).stream() : null)
            .toList();
        System.out.println("null from the mapper: " + found);

        // 2. Each inner stream is closed after use, so onClose handlers run
        List<String> closed = new ArrayList<>();
        long count = Stream.of("f1", "f2", "f3")
            .flatMap(f -> Stream.of(f + ":line1", f + ":line2").onClose(() -> closed.add(f)))
            .count();
        System.out.println(count + " lines, inner streams closed: " + closed);

        // 3. Returning the same stream object twice fails: a stream can be used only once
        Stream<String> shared = Stream.of("p", "q");
        try {
            Stream.of(1, 2).flatMap(i -> shared).toList();
        } catch (IllegalStateException e) {
            System.out.println("reused inner stream: IllegalStateException, " + e.getMessage());
        }

        // 4. map on an Optional-returning function nests; flatMap does not
        Optional<String> user = Optional.of("ann");
        Optional<Optional<String>> nested = user.map(FlatMapTraps::email);
        Optional<String> flat = user.flatMap(FlatMapTraps::email);
        System.out.println("Optional.map: " + nested + ", Optional.flatMap: " + flat);

        // 5. Recursion flattens any depth
        Node root = new Node("root", List.of(
            new Node("src", List.of(new Node("Main.java", List.of()))),
            new Node("docs", List.of(new Node("a.md", List.of()), new Node("b.md", List.of())))));
        System.out.println("whole tree: " + root.flatten().map(Node::name).toList());
    }

    static Optional<String> email(String name) {
        return Optional.of(name + "@example.com");
    }
}
Output
null from the mapper: [x, y]
6 lines, inner streams closed: [f1, f2, f3]
reused inner stream: IllegalStateException, stream has already been operated upon or closed
Optional.map: Optional[Optional[ann@example.com]], Optional.flatMap: Optional[ann@example.com]
whole tree: [root, src, Main.java, docs, a.md, b.md]
  • The mapper returned null for the missing key b, and the result was just [x, y] with no exception. The documentation says a null mapped stream is replaced by an empty one. It works, but Stream.empty() says the same thing clearly and does not depend on that rule.
  • All three inner streams ran their onClose handlers, recorded as [f1, f2, f3], after their two lines each had been passed on. flatMap closes every stream it receives, so mapping each file name to Files.lines(path) releases each file handle without a separate try-with-resources per file.
  • Returning the same Stream object for two elements threw IllegalStateException: "stream has already been operated upon or closed". The mapper must build a fresh stream on each call, for example from a collection with list.stream().
  • Optional.map with a function that itself returns an Optional gave Optional[Optional[ann@example.com]]. Optional.flatMap removed the extra layer. The rule is the same as for streams: use flatMap when the function already returns the container type.
  • A record method that calls flatMap on itself walked a tree of any depth and listed all six nodes in depth-first order, parent before children. Very deep trees can overflow the call stack this way, so use an explicit ArrayDeque as a work list for data nested thousands of levels deep.

Flattening maps: inverted indexes and nested maps

Flattening a map is harder than flattening a list, because each value usually means something only together with its key. The trick is to carry the key into the inner stream, most simply by pairing it with each value in a Map.entry. The program builds an inverted index and turns a map of maps into rows.

Java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class InvertIndex {

    public static void main(String[] args) {
        // Which tags does each article have?
        Map<String, List<String>> articleTags = new TreeMap<>(Map.of(
            "intro", List.of("java", "basics"),
            "streams", List.of("java", "streams", "lambdas"),
            "threads", List.of("java", "concurrency")));

        // Flip it: which articles have each tag? Keep the key next to every value.
        Map<String, TreeSet<String>> tagArticles = articleTags.entrySet().stream()
            .flatMap(e -> e.getValue().stream().map(tag -> Map.entry(tag, e.getKey())))
            .collect(Collectors.groupingBy(Map.Entry::getKey, TreeMap::new,
                Collectors.mapping(Map.Entry::getValue, Collectors.toCollection(TreeSet::new))));
        System.out.println("tag -> articles: " + tagArticles);

        // A map of maps becomes one row per inner entry
        Map<String, Map<String, Integer>> sales = new TreeMap<>(Map.of(
            "2024", new TreeMap<>(Map.of("q1", 10, "q2", 14)),
            "2025", new TreeMap<>(Map.of("q1", 12))));
        List<String> rows = sales.entrySet().stream()
            .flatMap(y -> y.getValue().entrySet().stream()
                .map(q -> y.getKey() + "," + q.getKey() + "," + q.getValue()))
            .toList();
        System.out.println("CSV rows: " + rows);
    }
}
Output
tag -> articles: {basics=[intro], concurrency=[threads], java=[intro, streams, threads], lambdas=[streams], streams=[streams]}
CSV rows: [2024,q1,10, 2024,q2,14, 2025,q1,12]
  • Each article's tag list was flattened into (tag, article) pairs, and groupingBy on the tag gathered the articles back. java mapped to all three articles, [intro, streams, threads], and every other tag to one.
  • Without the Map.entry, the inner stream would have produced bare tags, and the article name would have been lost by the time the collector ran. The lambda inside flatMap is the only place where both the key and the value are in scope.
  • Map.entry (Java 9) creates an immutable pair that rejects null. For older code or null values, new AbstractMap.SimpleEntry<>(k, v) does the same job, and a small record gives the two fields readable names.
  • The nested sales map became three CSV rows, 2024,q1,10, 2024,q2,14 and 2025,q1,12. The outer key was captured by the inner map lambda, so one flatMap replaced two nested loops.
  • The rows came out in year and quarter order only because both levels were TreeMaps. A HashMap at either level would have produced the same rows in an unspecified order.

When to use flatMap

Choosing a flattening approach
SituationUse
A list of lists into one listflatMap(List::stream)
Values of a map of listsmap.values().stream().flatMap(List::stream)
Lines into wordsflatMap(line -> Arrays.stream(line.split("\\s+")))
Drop empty OptionalsflatMap(Optional::stream)
Chained optional lookupsoptional.flatMap(...)
Flatten inside a groupingCollectors.flatMapping
Characters or numbers from many sourcesflatMapToInt
Zero or one result per element, or complex emissionmapMulti
One result per elementmap, not flatMap

For grouping flattened data, see the groupingBy page.