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
mapflatMapflatMap
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.
| Method | Since | Best for |
|---|---|---|
Stream.flatMap | Java 8 | Flattening nested collections; one-to-many mappings |
flatMapToIntflatMapToLongflatMapToDouble | Java 8 | Flattening into primitive streams without boxing |
Optional.flatMap | Java 8 | Chaining lookups that each return an Optional |
Optional.stream | Java 9 | Dropping empty results in a stream |
Collectors.flatMapping | Java 9 | Flattening inside groupingBypartitioningBy |
Stream.mapMulti | Java 16 | One-to-many without creating a stream per element |
Every program on this page ran on JDK 21. Streams in general are introduced on the
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.
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:
map: [[pen, ink], [paper], [], [pen, stapler]]
flatMap: [pen, ink, paper, pen, stapler]
distinct sorted: [ink, paper, pen, stapler]
total items: 5
gave a list of four lists, including the empty one: the nesting is kept.map(Order::items) gave one list of five items, and the empty order contributed nothing.flatMap(o -> o.items().stream())- After flattening, the usual stream operations apply to the individual items:
anddistinct removed the duplicate pen, andsorted totalled all items across orders.count
Common patterns
Five short examples cover the situations where flatMapmapMulti
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:
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
and flattening turns a list of lines into a list of words.Arrays.stream(line.split(" ")) - Parsing each string into an
and flattening withOptional<Integer> keeps the numbers that parsed and drops the rest, in one step.Optional::stream collects all members of a map of lists.teams.values().stream().flatMap(List::stream)- A nested
over sizes and colours generates every combination, the stream form of two nested loops.flatMap , from Java 16, passes each element and a sink to a function that callsmapMulti once per result. It avoids creating a small stream for every element, and the type witnesssink.accept tells the compiler the result type.<Integer>
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.
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:
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
gives totals across all orders: 7 pens.summingInt (Java 9) flattens inside a downstream collector, here listing the products of orders with more than one line separately from the rest.Collectors.flatMapping chains a lookup that itself returns anOptional.flatMap , givingOptional rather thanOptional<Line> .Optional<Optional<Line>> turns several strings into oneflatMapToInt(String::chars) of characters without boxing, summing the digits 1 to 5 to 15.IntStream- Pairs
come from a flatMap over a range that starts afteri < j , the stream version of a triangular nested loop.i
flatMap is lazy
Current JDKs make flatMaplimitfindFirst
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:
[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
stopped the pipeline after the first three.limit(3) - The inner stream from
never ends, yetStream.iterate(start, i -> i + 1) returned 14 immediately. On a JDK without the fix, the same code never finishes.findFirst - 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.
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):
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.
per list grows the target in many steps, and nested loops add one element at a time; neither had a consistent advantage.addAll avoids the per-element stream, which matters most for mappings that produce zero or one result, or that would otherwise build a temporary collection.mapMulti
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
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");
}
}
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
for the missing keynull , and the result was justb with no exception. The documentation says a[x, y] mapped stream is replaced by an empty one. It works, butnull says the same thing clearly and does not depend on that rule.Stream.empty() - All three inner streams ran their
handlers, recorded asonClose , after their two lines each had been passed on.[f1, f2, f3] closes every stream it receives, so mapping each file name toflatMap releases each file handle without a separate try-with-resources per file.Files.lines(path) - Returning the same
object for two elements threwStream : "stream has already been operated upon or closed". The mapper must build a fresh stream on each call, for example from a collection withIllegalStateException .list.stream() with a function that itself returns anOptional.map gaveOptional .Optional[Optional[ann@example.com]] removed the extra layer. The rule is the same as for streams: useOptional.flatMap when the function already returns the container type.flatMap- A record method that calls
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 explicitflatMap as a work list for data nested thousands of levels deep.ArrayDeque
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
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);
}
}
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
pairs, and(tag, article) on the tag gathered the articles back.groupingBy mapped to all three articles,java , and every other tag to one.[intro, streams, threads] - Without the
, the inner stream would have produced bare tags, and the article name would have been lost by the time the collector ran. The lambda insideMap.entry is the only place where both the key and the value are in scope.flatMap (Java 9) creates an immutable pair that rejectsMap.entry . For older code ornull values,null does the same job, and a small record gives the two fields readable names.new AbstractMap.SimpleEntry<>(k, v)- The nested sales map became three CSV rows,
,2024,q1,10 and2024,q2,14 . The outer key was captured by the inner2025,q1,12 lambda, so onemap replaced two nested loops.flatMap - The rows came out in year and quarter order only because both levels were
s. ATreeMap at either level would have produced the same rows in an unspecified order.HashMap
When to use flatMap
| Situation | Use |
|---|---|
| A list of lists into one list | flatMap(List::stream) |
| Values of a map of lists | map.values().stream().flatMap(List::stream) |
| Lines into words | flatMap(line -> Arrays.stream(line.split("\\s+"))) |
| Drop empty Optionals | flatMap(Optional::stream) |
| Chained optional lookups | optional.flatMap(...) |
| Flatten inside a grouping | Collectors.flatMapping |
| Characters or numbers from many sources | flatMapToInt |
| Zero or one result per element, or complex emission | mapMulti |
| One result per element | mapflatMap |
For grouping flattened data, see the