Java Stream flatMap and Stream.concat: Flattening and Combining Streams
flatMap() is an intermediate Stream API operation (Java 8) with the signature flatMap(Function<T, Stream<R>>): it turns every element into a stream of zero, one or many elements and joins those streams into one flat stream. Stream.concat(a, b) is a static method that lazily combines two streams: first all elements of the first one, then all elements of the second. You use the first to flatten nested structures (a list of lists, orders with their line items, lines with words) and the second to merge two sources into a single pipeline.
The most common beginner mistake looks like this: you want the words from a list of sentences, you write map(s -> Arrays.stream(s.split(" "))), and the console shows java.util.stream.ReferencePipeline$Head@4e50df2e instead of words (the hash differs on every run). The code compiled and nothing was thrown, but every element of the result is a whole stream, not a string. Why that happens and how flatMap() fixes it is in flatMap vs map: the difference.
1. How flatMap() works
flatMap() calls the mapper function for every element, gets a stream back and passes all elements of that stream down the pipeline one by one. One input element may produce zero output elements (an empty stream), one, or any number. The result is an ordinary Stream<R> with no nesting.
The full signature is stricter than the definition above:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) What matters is the return type of the function: a Stream, not a single value. With map() the function returns R, and there are exactly as many output elements as input ones. With flatMap() the function returns a stream, and the number of output elements can be anything.
Here is the picture for three orders with 2, 0 and 3 line items:
order 1 -> [pen, notebook]
order 2 -> []
order 3 -> [pen, ruler, eraser]
flatMap -> pen, notebook, pen, ruler, eraser This is the very example the JDK Javadoc uses: orders.flatMap(order -> order.getLineItems().stream()) produces a stream of all line items of all orders. Order is preserved: first every element of the first nested stream, then the second, and so on. An order with no line items simply adds nothing.
flatMap() is a stateless intermediate operation, like map() and filter(): it remembers nothing about previous elements. The overall table of intermediate operations is in Intermediate operations, and the stateless/stateful distinction in Stateless and stateful operations.
2. flatMap vs map: the difference
The difference between map and flatMap is what the function returns. map() turns each element into exactly one new element, so if the function returns a list, an array or a stream, the result becomes nested: Stream<List<T>>, Stream<String[]>, Stream<Stream<T>>. flatMap() expects a stream from the function and unpacks it, so the result is flat.
| Aspect | map() | flatMap() |
|---|---|---|
| What the function returns | One value R | A stream Stream<R> |
| Output elements per input element | Exactly 1 | 0, 1 or N |
Sentences → s.split(" ") | Stream<String[]> — a stream of arrays | Stream<String> — a stream of words (with Arrays.stream(...)) |
List of lists → List::stream | Stream<Stream<T>> | Stream<T> |
| Typical task | Transform each element: a string into its length, an employee into a name | Remove nesting: orders into line items, lines into words |
| Primitive variants | mapToInt, mapToLong, mapToDouble | flatMapToInt, flatMapToLong, flatMapToDouble |
Here is the difference on the same set of sentences:
// MapVsFlatMap.java
import java.util.Arrays;
import java.util.List;
public class MapVsFlatMap {
public static void main(String[] args) {
List<String> sentences = List.of("Java is fun", "Streams are lazy");
// map: each sentence -> one array
List<String[]> arrays = sentences.stream()
.map(s -> s.split(" "))
.toList();
System.out.println(arrays.size());
System.out.println(Arrays.toString(arrays.get(0)));
// flatMap: each sentence -> a stream of words, the streams are joined
List<String> words = sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.toList();
System.out.println(words.size());
System.out.println(words);
}
} 2
[Java, is, fun]
6
[Java, is, fun, Streams, are, lazy] With map() you get two elements — two arrays — and have to dig into them with get(0) to reach the words. With flatMap() you get six words in one list. Note that flatMap(s -> s.split(" ")) does not compile: the function must return a stream, so the array is wrapped in Arrays.stream(). The Javadoc shows the same trick for splitting file lines into words, with Stream.of(line.split(" +")).
3. Common patterns: list of lists, arrays, strings, Optional
In practice flatMap() almost always shows up in one of five patterns: flatten a list of lists into one list (flatMap(List::stream)), nested collections of objects (order -> order.items().stream()), the values of a Map (map.values().stream().flatMap(Collection::stream)), a two-dimensional array (flatMap(Arrays::stream)) and dropping empty Optionals (flatMap(Optional::stream)).
Flatten a list of lists into one list
// FlattenDemo.java
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class FlattenDemo {
record Item(String name, int qty) { }
record Order(int id, List<Item> items) { }
public static void main(String[] args) {
// 1. List<List<Integer>> -> List<Integer>
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(), List.of(4, 5));
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.toList();
System.out.println(flat);
// 2. orders -> order line items
List<Order> orders = List.of(
new Order(1, List.of(new Item("pen", 2), new Item("notebook", 1))),
new Order(2, List.of()),
new Order(3, List.of(new Item("pen", 5))));
int pens = orders.stream()
.flatMap(order -> order.items().stream())
.filter(item -> item.name().equals("pen"))
.mapToInt(Item::qty)
.sum();
System.out.println("pens: " + pens);
// 3. all values of a Map<String, List<String>> without duplicates
Map<String, List<String>> skillsByTeam = new TreeMap<>();
skillsByTeam.put("backend", List.of("Java", "SQL"));
skillsByTeam.put("qa", List.of("SQL", "Selenium"));
Set<String> skills = skillsByTeam.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(skills);
}
} [1, 2, 3, 4, 5]
pens: 7
[Java, SQL, Selenium] An empty inner list and an order with no items break nothing — they produce an empty stream and simply add no elements. In the third example SQL belongs to two teams but appears once in the result: the TreeSet removed the duplicate. If you need the keys as well as the values, go through entrySet() — there is an example in the FAQ.
A similar task inside a grouping — collect all skills for each department — is solved not with flatMap() but with the Collectors.flatMapping() collector (Java 9) as a downstream of groupingBy(); it is covered in minBy, maxBy, mapping, reducing, collectingAndThen.
Arrays, string characters and Optional
// FlatMapSourcesDemo.java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FlatMapSourcesDemo {
static Optional<String> findEmail(int userId) {
return userId % 2 == 0 ? Optional.of("user" + userId + "@mail.com") : Optional.empty();
}
public static void main(String[] args) {
// two-dimensional array -> flat list
String[][] table = {{"a", "b"}, {"c"}, {}};
List<String> cells = Arrays.stream(table)
.flatMap(Arrays::stream)
.toList();
System.out.println(cells);
// strings -> characters: unique letters of two words in alphabetical order
String letters = Stream.of("java", "stream")
.flatMapToInt(String::chars)
.distinct()
.sorted()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println(letters);
// Optional::stream: empty Optionals simply disappear
List<String> emails = Stream.of(1, 2, 3, 4)
.map(FlatMapSourcesDemo::findEmail)
.flatMap(Optional::stream)
.toList();
System.out.println(emails);
}
} [a, b, c]
aejmrstv
[user2@mail.com, user4@mail.com] String.chars() returns an IntStream of character codes, not a Stream<Character>, which is why flatMapToInt() is needed here; for printing, the codes are turned back into characters with (char) c. Optional.stream() arrived in Java 9: for an empty Optional it returns an empty stream, for a non-empty one a stream of one element (more in or() and stream()). Do not confuse it with Optional.flatMap(): that is a method of Optional itself which removes the nesting in Optional<Optional<T>>, covered in Transformation: map, flatMap, filter.
Before Java 9
In Java 8 code the same selection is written as the pair filter(Optional::isPresent).map(Optional::get). It works, but a get() call separated from its check is easy to break during refactoring. On Java 9+ a single flatMap(Optional::stream) does the same job and has no get() at all.
4. flatMapToInt and the other primitive variants
When the nested streams are primitive, plain flatMap() does not fit: its function must return a Stream, while Arrays.stream(int[]) and String.chars() return an IntStream. For this case Stream has flatMapToInt(), flatMapToLong() and flatMapToDouble(), and the primitive streams have their own flatMap() that returns a stream of the same primitive type.
| Method | Function returns | Result | Example |
|---|---|---|---|
Stream.flatMap() | Stream<R> | Stream<R> | flatMap(List::stream) |
Stream.flatMapToInt() | IntStream | IntStream | flatMapToInt(Arrays::stream) for int[][], flatMapToInt(String::chars) |
Stream.flatMapToLong() | LongStream | LongStream | flatMapToLong(Arrays::stream) for long[][] |
Stream.flatMapToDouble() | DoubleStream | DoubleStream | Parsing numbers out of strings |
IntStream.flatMap() (also on LongStream, DoubleStream) | IntStream | IntStream | range(1, 4).flatMap(n -> IntStream.range(0, n)) |
Stream.mapMultiToInt() (Java 16) | nothing: elements are passed to an IntConsumer | IntStream | see mapMulti() |
// PrimitiveFlatMapDemo.java
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PrimitiveFlatMapDemo {
public static void main(String[] args) {
// sum of all numbers in nested arrays
int[][] matrix = {{1, 2, 3}, {4, 5}, {}, {6}};
int sum = Arrays.stream(matrix)
.flatMapToInt(Arrays::stream)
.sum();
System.out.println(sum);
// IntStream.flatMap: for n = 1, 2, 3 emit 0..n-1
int[] steps = IntStream.rangeClosed(1, 3)
.flatMap(n -> IntStream.range(0, n))
.toArray();
System.out.println(Arrays.toString(steps));
// space-separated numbers in strings; an empty string does not break parsing
double total = Stream.of("1.5 2.5", "3", "")
.flatMapToDouble(line -> Arrays.stream(line.split(" "))
.filter(s -> !s.isEmpty())
.mapToDouble(Double::parseDouble))
.sum();
System.out.println(total);
}
} 21
[0, 0, 1, 0, 1, 2]
7.0 Why the last example needs filter(): "".split(" ") returns not an empty array but an array holding one empty string, and Double.parseDouble("") would throw NumberFormatException: empty String. For int[][], flatMap(Arrays::stream) does not compile: Arrays.stream(int[]) returns an IntStream, and flatMap() requires a Stream. If you really need a Stream<Integer>, write flatMap(row -> Arrays.stream(row).boxed()).
5. How flatMap behaves: closing, null and laziness
The JDK 25 Javadoc gives flatMap() three guarantees that tutorials rarely mention: each nested stream is closed right after its elements have been passed on; if the function returns null, an empty stream is used and no NullPointerException occurs; and since Java 10 nested streams are read lazily, so findFirst() and limit() work even with infinite nested streams.
// FlatMapBehaviorDemo.java
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class FlatMapBehaviorDemo {
public static void main(String[] args) {
// 1. nested streams are closed, null becomes an empty stream
List<String> result = Stream.of("a", "b", "c")
.flatMap(s -> s.equals("b")
? null
: Stream.of(s, s.toUpperCase()).onClose(() -> System.out.println("closed " + s)))
.toList();
System.out.println(result);
// 2. infinite nested streams + findFirst
AtomicInteger seen = new AtomicInteger();
int first = Stream.of(1, 2)
.flatMap(n -> Stream.iterate(n * 10, x -> x + 1))
.peek(x -> seen.incrementAndGet())
.filter(x -> x > 12)
.findFirst()
.orElseThrow();
System.out.println("first = " + first + ", seen = " + seen.get());
// 3. infinite nested streams + limit
System.out.println(Stream.of("a", "b")
.flatMap(s -> Stream.generate(() -> s))
.limit(3)
.toList());
}
} closed a
closed c
[a, A, c, C]
first = 13, seen = 4
[a, a, a] The lines closed a and closed c are printed before the list: a nested stream is closed as soon as it has handed over its elements, not at the end of the pipeline. That matters when a nested stream holds a resource — for example, flatMap(path -> Files.lines(path)) over a list of files closes each file as soon as it has been read to the end. For "b" the function returned null, and the element simply vanished from the result. Do not rely on that in your own code: Stream.empty() reads more clearly and will not surprise whoever maintains the code next.
In the second example the first nested stream is infinite: 10, 11, 12, 13, … The pipeline read exactly four elements from it, found 13 and stopped; the second nested stream was never started. The third example shows the same with limit(): three elements were taken from the infinite stream of a, and b never began.
Java 8 and 9 behave differently
In Java 8 and 9 flatMap() drained every nested stream completely without checking whether downstream still needed elements: findFirst() and limit() could not cut a nested stream short (bug JDK-8075939, fixed in Java 10). On those versions examples 2 and 3 above never finish, and finite but large nested streams do unnecessary work. If your project is still on Java 8, do not feed infinite or expensive streams into flatMap() expecting an early stop.
6. mapMulti(): the Java 16 alternative to flatMap
mapMulti() (Java 16) performs the same "one element → zero or more" transformation, but instead of returning a stream, the function receives the element and a Consumer and hands results to it with accept() calls. The signature is <R> Stream<R> mapMulti(BiConsumer<? super T, ? super Consumer<R>> mapper). For primitives there are mapMultiToInt(), mapMultiToLong() and mapMultiToDouble().
The Javadoc names two cases where mapMulti() is preferable to flatMap(). The first is when each element is replaced by a small number of elements, often zero or one: flatMap() creates a new Stream object per element, mapMulti() does not. The second is when the result is easier to produce with imperative code (conditions, loops, recursion) than to assemble into a stream.
// MapMultiDemo.java
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class MapMultiDemo {
// recursively expands nested Iterables
static void expand(Object element, Consumer<Object> sink) {
if (element instanceof Iterable<?> items) {
for (Object item : items) {
expand(item, sink);
}
} else if (element != null) {
sink.accept(element);
}
}
public static void main(String[] args) {
// 1. keep only the Integers of a Stream<Number>: filter and cast in one step
Stream<Number> numbers = Stream.of(1, 2.5, 3L, 4, 5.0f);
List<Integer> integers = numbers.<Integer>mapMulti((number, sink) -> {
if (number instanceof Integer i) {
sink.accept(i);
}
}).toList();
System.out.println(integers);
// 2. nested lists of any depth
List<Object> nested = List.of(1, List.of(2, List.of(3, 4)), 5);
List<Object> flat = nested.stream()
.mapMulti(MapMultiDemo::expand)
.toList();
System.out.println(flat);
// 3. one element -> two
List<String> both = Stream.of("a", "b")
.<String>mapMulti((s, sink) -> {
sink.accept(s);
sink.accept(s.toUpperCase());
})
.toList();
System.out.println(both);
}
} [1, 4]
[1, 2, 3, 4, 5]
[a, A, b, B] With flatMap() the first example would read flatMap(n -> n instanceof Integer i ? Stream.of(i) : Stream.empty()) — a new stream per element just to carry zero or one value. The second would need a recursive function that returns streams, whereas with a Consumer it is an ordinary recursive traversal. Both examples come from the Javadoc of Stream.mapMulti() in JDK 25.
Why write .<Integer>mapMulti
The compiler cannot infer the result type R from the lambda: there is no return in it, only sink.accept() calls. Without an explicit type argument, numbers.mapMulti(...) gets R = Object, and assigning the result of toList() to a List<Integer> does not compile (List<Object> cannot be converted to List<Integer>). Set the type either with .<Integer>mapMulti(...) or with explicit lambda parameter types: (Number number, Consumer<Integer> sink) -> ....
One more restriction from the Javadoc: the Consumer may only be called inside the function, while it is running. Storing it in a field and calling it later gives undefined results. And if flattening needs state shared across elements — say, grouping elements into batches — neither flatMap() nor mapMulti() fits: that is a job for the gather() method from Java 24, which generalises the 1 → N transformation to stateful operations.
7. Stream.concat(): how to combine two streams
To combine two streams in Java, call the static method Stream.concat(a, b): it returns a new stream with all elements of a followed by all elements of b. Nothing is copied into an intermediate collection — concat() lazily pulls elements from the source streams as they are needed. For primitives there are IntStream.concat(), LongStream.concat() and DoubleStream.concat().
// ConcatDemo.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ConcatDemo {
public static void main(String[] args) {
List<String> backend = List.of("Anna", "Ben", "Clara");
List<String> frontend = List.of("Clara", "Dave");
// merge two lists into one
List<String> all = Stream.concat(backend.stream(), frontend.stream()).toList();
System.out.println(all);
// merge without duplicates
List<String> unique = Stream.concat(backend.stream(), frontend.stream())
.distinct()
.toList();
System.out.println(unique);
// primitive streams
int[] merged = IntStream.concat(IntStream.of(1, 2), IntStream.rangeClosed(8, 10)).toArray();
System.out.println(Arrays.toString(merged));
// parallel if at least one of the streams is parallel
boolean parallel = Stream.concat(backend.stream(), frontend.parallelStream()).isParallel();
System.out.println("parallel: " + parallel);
// closing the result closes both source streams
Stream<String> a = Stream.of("x").onClose(() -> System.out.println("close a"));
Stream<String> b = Stream.of("y").onClose(() -> System.out.println("close b"));
try (Stream<String> ab = Stream.concat(a, b)) {
System.out.println(ab.toList());
}
}
} [Anna, Ben, Clara, Clara, Dave]
[Anna, Ben, Clara, Dave]
[1, 2, 8, 9, 10]
parallel: true
[x, y]
close a
close b distinct() keeps the first occurrence, so Clara stays where she was in the first list. If you need a mutable result or merge two lists just once, a plain new ArrayList<>(a) plus addAll(b) is just as good; concat() wins when merging is part of a pipeline — filter(), map() or sorting follow, and no intermediate list is needed.
Properties of the result according to the JDK 25 Javadoc:
| Property | What concat(a, b) guarantees | What it means in practice |
|---|---|---|
| Order | All elements of a, then all elements of b | Elements of the two streams are never interleaved |
| Laziness | Elements are read as needed | If the first stream is infinite, the second never starts |
| Ordering (ORDERED) | Only if both streams are ordered | One HashSet among the sources and findFirst() is no longer predictable |
| Parallelism | Parallel if at least one stream is parallel | A later sequential() or parallel() does not necessarily reach the source streams |
| Closing | The close handlers of both streams are invoked | try-with-resources on the result is enough |
| Binding to the source | Both streams are bound to their sources at the moment of the call | a and b themselves cannot be used after concat() |
| Arguments | Exactly two streams | For three or more use flatMap(), see the next section |
8. More than two streams: flatMap instead of nested concat
To combine three or more streams, the Javadoc of Stream.concat() recommends not nesting the calls, but building a stream of streams and flattening it: Stream.of(s1, s2, s3).flatMap(Function.identity()), or equivalently flatMap(s -> s). For lists it is even simpler: Stream.of(list1, list2, list3).flatMap(List::stream).
Stream.concat(Stream.concat(s1, s2), s3) works fine for three streams. Trouble starts when there are many streams and the chain is built in a loop or with reduce(). In its implementation note (@implNote) the Javadoc warns that accessing an element of a deeply concatenated stream can result in deep call chains, or even StackOverflowError. Every concat() wraps the previous result, and reaching an element means descending through every level of nesting.
// ConcatManyDemo.java
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ConcatManyDemo {
static long viaFlatMap(int n) {
return IntStream.range(0, n)
.mapToObj(i -> Stream.of(i))
.flatMap(Function.identity())
.count();
}
static long viaConcat(int n) {
return IntStream.range(0, n)
.mapToObj(i -> Stream.of(i))
.reduce(Stream.empty(), Stream::concat) // concat(concat(concat(...)))
.count();
}
public static void main(String[] args) throws InterruptedException {
Runnable demo = () -> {
for (int n : new int[] {1_000, 10_000}) {
System.out.println(n + " flatMap: " + viaFlatMap(n));
try {
System.out.println(n + " concat: " + viaConcat(n));
} catch (StackOverflowError e) {
System.out.println(n + " concat: StackOverflowError");
}
}
};
// A thread with a 256 KB stack: the error reproduces quickly and at a small n
Thread thread = new Thread(null, demo, "small-stack", 256 * 1024);
thread.start();
thread.join();
}
} 1000 flatMap: 1000
1000 concat: 1000
10000 flatMap: 10000
10000 concat: StackOverflowError The example runs in a separate thread with a 256 KB stack so that the error shows up quickly. The threshold depends on the thread's stack size (-Xss or the stackSize parameter of the Thread constructor) and on the JVM: on JDK 25.0.3, in the main thread with the default stack, 10,000 nested concat() calls succeed and 50,000 already fail. There is a second problem you hit before the error: time grows quadratically. In the same run 10,000 nested concat() calls took about a second and 30,000 took more than ten seconds, while flatMap() finished in milliseconds at any of these sizes. The flatMap() version does not depend on depth: the streams are processed one after another rather than nested inside each other.
Ten thousand single-element streams is an artificial example, but the real-world form of the same bug does occur: merging results over a list of files, API pages or partitions in a loop like result = Stream.concat(result, next). With little data everything works; on a large volume it crashes. Rewrite such a loop right away as a list of streams plus flatMap().
9. Gotchas with flatMap and concat
Mistakes with flatMap() usually throw nothing and just give the wrong result: nested streams instead of elements, a single array element instead of numbers. Mistakes with concat(), on the contrary, tend to end in an exception: IllegalStateException when a stream is reused, or StackOverflowError with deep nesting.
| What people do | What happens | The fix |
|---|---|---|
map(s -> Arrays.stream(...)) instead of flatMap | Stream<Stream<String>>; printing shows java.util.stream.ReferencePipeline$Head@... | flatMap(s -> Arrays.stream(...)) |
Pass concat() a stream that has already been used (including by another concat()) | IllegalStateException: stream has already been operated upon or closed — right at the concat() call | Create the stream again or keep a Supplier<Stream<T>> |
Stream.of(intArray) or Arrays.asList(intArray) for an int[] | One element — the array itself: Stream<int[]>, List<int[]> | Arrays.stream(intArray), IntStream.of(intArray); for a list see Arrays.asList() with a primitive array |
flatMap(Arrays::stream) for an int[][] | Compilation error: Arrays.stream(int[]) returns an IntStream | flatMapToInt(Arrays::stream) |
Pass an infinite stream as the first argument of concat() | The second stream never starts; without limit() — an endless loop | Bound the first stream or swap the arguments |
Build concat() in a loop or with reduce() | Deep nesting; StackOverflowError on large volumes | Stream.of(...).flatMap(Function.identity()) (section 8) |
mapMulti() without an explicit result type | Stream<Object>; assigning to a List<Integer> does not compile | .<Integer>mapMulti(...) |
Here is the first row in practice — the code compiles and prints something, just not what you wanted:
List.of("Java is fun", "Streams are lazy").stream()
.map(s -> Arrays.stream(s.split(" ")))
.forEach(System.out::println);
// java.util.stream.ReferencePipeline$Head@4e50df2e
// java.util.stream.ReferencePipeline$Head@1d81eb93
// (the hash codes after @ change from run to run) The second row is surprising for a different reason. People associate single-use streams with terminal operations (the general rule is in Where developers get tripped up). But concat() is not a terminal operation, and it is concat() that throws — at the moment of the call, not when execution reaches toList():
// ConcatReuseDemo.java
import java.util.stream.Stream;
public class ConcatReuseDemo {
public static void main(String[] args) {
Stream<String> base = Stream.of("a", "b");
Stream<String> withC = Stream.concat(base, Stream.of("c"));
try {
Stream<String> withD = Stream.concat(base, Stream.of("d")); // base is already bound to withC
System.out.println(withD.toList());
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
System.out.println(withC.toList());
}
} IllegalStateException: stream has already been operated upon or closed
[a, b, c] This happens because concat() immediately takes the spliterator() of both streams — that is the "binding to the source" from the properties table. No elements have been read yet, but the base object itself is already used up. The first concat() call went through normally, and withC is still usable. If a base set has to be attached to several different streams, keep a Supplier<Stream<String>> base = () -> Stream.of("a", "b") and call base.get() for each concat().
10. What arrived in which Java version
flatMap(), its primitive variants and Stream.concat() have existed since Java 8. Later came Optional.stream() and Collectors.flatMapping() (Java 9), lazy flatMap() with short-circuiting operations (Java 10), and mapMulti() together with Stream.toList() (Java 16). All examples in this lesson use toList() and pattern matching for instanceof, so they need Java 16+.
| Version | What arrived | How it was written before |
|---|---|---|
| Java 8 | Stream.flatMap(), flatMapToInt/Long/Double(), IntStream.flatMap(), Stream.concat(), IntStream.concat() | Nested loops and addAll() |
| Java 9 | Optional.stream(), Collectors.flatMapping() | filter(Optional::isPresent).map(Optional::get) |
| Java 10 | flatMap() cuts a nested stream short on findFirst(), limit(), anyMatch() (JDK-8075939) | The nested stream was drained completely |
| Java 16 | mapMulti(), mapMultiToInt/Long/Double(), Stream.toList() | flatMap() with Stream.of(...) / Stream.empty(); collect(Collectors.toList()) |
| Java 24 | Stream.gather() — a stateful 1 → N transformation | Indexes, collect() and a new stream, a loop |
On Java 8–15 the flatMap() and concat() examples work if you replace toList() with collect(Collectors.toList()) and instanceof Integer i with a check plus an explicit cast; on Java 8–9 the examples with infinite nested streams from section 5 will not work. The full method contracts are in the Stream interface Javadoc (JDK 25).
Frequently asked questions
How do I merge three or more lists into one list?
Put the lists into a stream and flatten it: Stream.of(list1, list2, list3).flatMap(List::stream).toList(). If the lists already sit in a List<List<T>>, use lists.stream().flatMap(List::stream).toList(). Nested Stream.concat() calls are the wrong tool: with many sources they run into the stack depth limit — details in More than two streams.
How do I flatten a Map<String, List<String>> into key-value pairs?
Use entrySet() and a nested map() inside flatMap(): map.entrySet().stream().flatMap(e -> e.getValue().stream().map(v -> e.getKey() + "=" + v)). For {"qa": ["SQL", "Selenium"]} you get qa=SQL, qa=Selenium. The key is available inside the lambda because a nested stream is created separately for each entry. If you only need the values, map.values().stream().flatMap(Collection::stream) is enough.
Does flatMap preserve the order of elements?
Yes, if the source stream is ordered: first all elements of the first nested stream, then the second, and so on. In a parallel stream the order is kept by toList(), collect() and forEachOrdered(), while forEach() does not guarantee it. If the nested streams come from unordered collections such as HashSet, the order inside each of them is whatever the collection gives.
What is the difference between Optional.flatMap and Stream.flatMap?
They are different methods sharing one idea: remove an extra level of nesting. Optional.flatMap() takes a function that returns an Optional and keeps you from ending up with Optional<Optional<T>>. Stream.flatMap() takes a function that returns a Stream. They meet in the idiom stream.flatMap(Optional::stream), which drops empty Optionals — see the example in Arrays, string characters and Optional.
Which is better for merging two lists: Stream.concat or addAll?
If all you need is a mutable combined list, use new ArrayList<>(a) and addAll(b): it is simpler and gives you an ArrayList straight away. Stream.concat(a.stream(), b.stream()) is handier when the merge is part of a pipeline: filter(), distinct(), sorted() follow and no intermediate list is created. Keep in mind that toList() at the end returns an unmodifiable list.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
- flatMap: order items, tags, Optional and int[][]
- Stream.concat, flatMap instead of a concat loop, and mapMulti
Comments