Quick revision
The short answer
orders.stream().flatMap(o -> o.lines().stream()).map(Line::productId).distinct().toList() gives the distinct product ids across all orders. map transforms each element into exactly one element, so using it here would give a Stream<List<Line>>; flatMap transforms each element into a stream and joins all those streams into one, giving a Stream<Line>. Since Java 16, mapMulti is an alternative that pushes elements to a consumer without creating a stream per element.
What to remember
In this answer, we collected the distinct product ids across all orders with flatMap(o -> o.lines().stream()), map(Line::productId), distinct() and toList(). We saw that map produces exactly one element per input, so it would give a Stream<List<Line>> or even a stream of streams, while flatMap produces zero or more elements per input by joining the inner streams into one. We also looked at ordering, sorted alternatives and null lists, and at mapMulti from Java 16, which pushes results to a consumer without creating a stream per element.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
orders.stream().flatMap(o -> o.lines().stream()).map(Line::productId).distinct().toList() gives the distinct product ids across all orders. map transforms each element into exactly one element, so using it here would give a Stream<List<Line>>; flatMap transforms each element into a stream and joins all those streams into one, giving a Stream<Line>. Since Java 16, mapMulti is an alternative that pushes elements to a consumer without creating a stream per element.
Why this question is asked
Nested data is everywhere: orders with lines, customers with addresses, departments with employees. Sooner or later we need something from the inner level across all outer elements, and that is precisely what flatMap is for. It is also the stream operation people most often confuse with map, which is why interviewers pair this small coding task with the question about the difference. In this answer, we will recap the data model, write the solution, see what goes wrong with map, look at how flatMap joins the streams, discuss ordering and distinct, and finish with mapMulti.
1A Quick Recap of the Data
We have orders, and each order has a list of lines; each line names a product. The task is one list of product ids, without duplicates, across all orders. We will use this small data set.
2The Solution
We flatten the lines of all orders into one stream, take the product id of each line, drop duplicates and collect.
Notice that the empty order o3 simply contributes nothing: its lines produce an empty stream, and flatMap joins it in without any special handling. distinct() uses equals() on the ids, so it works for Strings and records. toList() returns an unmodifiable list, which suits a result like this.
3What Goes Wrong With map
map transforms each element into exactly one new element. If we write map(o -> o.lines()), each order becomes one List<Line>, so we get a stream of lists, not a stream of lines.
Notice the last line: even mapping to a stream does not help, because map does not unpack what it returns. That unpacking step, taking the elements out of each inner stream and putting them into the outer one, is the only thing flatMap adds.
4How flatMap Joins the Streams
flatMap takes a function that returns a stream for each element. For every incoming order, it calls the function, gets the stream of that order's lines, and pushes each line downstream in order, then moves on to the next order. Since Java 10, flatMap is also lazy with respect to short-circuiting, so with findFirst after it, it stops pulling from the inner stream as soon as an answer is found. The inner streams are closed after their contents have been placed into the outer stream.
| After | Elements | Type |
|---|---|---|
orders.stream() | o1, o2, o3 | Stream<Order> |
map(Order::lines) | [p1, p2], [p2, p3], [] | Stream<List<Line>> |
flatMap(o -> o.lines().stream()) | p1, p2, p2, p3 (as Lines) | Stream<Line> |
map(Line::productId) | "p1", "p2", "p2", "p3" | Stream<String> |
distinct() | "p1", "p2", "p3" | Stream<String> |
So the one-to-many shape is the key difference: map is one in, one out; flatMap is one in, zero or more out. The table shows the stream at each step for our data.
5Order, Duplicates and Variations
distinct() keeps the first occurrence of each id in encounter order, so the result follows the order of orders and lines. If we want the ids sorted instead, we add sorted() or collect into a TreeSet with Collectors.toCollection(TreeSet::new). If order does not matter and we want a Set type, Collectors.toSet() is fine.
If the lines list may be null in some orders, for example from a poorly mapped entity, o.lines().stream() throws NullPointerException. A defensive version is flatMap(o -> o.lines() == null ? Stream.empty() : o.lines().stream()), though fixing the model so that lines is never null is better.
6The Alternative: mapMulti (Java 16)
mapMulti does the same one-to-many job differently. Instead of returning a stream for each element, our function receives the element and a consumer, and pushes zero or more results into the consumer. No stream object is created per element.
Notice the explicit type witness <String> before mapMulti: the compiler often cannot infer the result type from the lambda, so we state it. The documentation suggests mapMulti when each element maps to a small number of results, where creating a stream per element is relatively costly, or when it is easier to produce results imperatively, such as with a loop or a condition. For everyday code, flatMap is more familiar and usually clear enough.
7Follow-up questions
What does flatMap do on Optional?
Optional.flatMap takes a function that returns an Optional and avoids nesting, so we get Optional<T> instead of Optional<Optional<T>>. It is the same idea, one level of wrapping removed, applied to a container of zero or one element.
Is flatMap slower than a nested loop?
A little, because it creates a stream object per outer element. For most business code the difference is negligible. In hot paths with many small inner collections, mapMulti or a nested loop can be faster, so measure if it matters.
How would you count the total quantity per product instead?
Flatten to lines and group: orders.stream().flatMap(o -> o.lines().stream()).collect(groupingBy(Line::productId, summingInt(Line::qty))) gives {p1=2, p2=6, p3=1}. Flattening first and then collecting is the general pattern for aggregating nested data.
8Conclusion
In this answer, we collected the distinct product ids across all orders with flatMap(o -> o.lines().stream()), map(Line::productId), distinct() and toList(). We saw that map produces exactly one element per input, so it would give a Stream<List<Line>> or even a stream of streams, while flatMap produces zero or more elements per input by joining the inner streams into one. We also looked at ordering, sorted alternatives and null lists, and at mapMulti from Java 16, which pushes results to a consumer without creating a stream per element.
Open with
I'd write orders stream, flatMap of o arrow o lines stream, then map Line colon colon productId, distinct, and toList. flatMap turns the stream of orders into one stream of all their lines, map takes each line's product id, distinct removes duplicates using equals, keeping the first occurrence in encounter order, and toList gives an unmodifiable list.
Then, if they want more
An order with no lines just contributes an empty stream, so it needs no special handling. The difference from map is the shape: map is one in, one out.
If I used map with Order lines here, I'd get a Stream of List of Line, three lists, and I couldn't call productId on them; and if I mapped to o lines stream, I'd get a stream of streams, because map doesn't unpack what the function returns. flatMap expects the function to return a stream for each element and joins all those inner streams into one, so it's one in, zero or more out.
If I wanted the ids sorted I'd add sorted or collect into a TreeSet. Since Java 16 there's also mapMulti, where instead of returning a stream, my lambda gets the element and a consumer and pushes results into it, for example a for loop over the lines calling sink accept with the product id.
That avoids creating a stream per element, which helps when each element produces only a few results, though for everyday code flatMap is more familiar.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16, Java 10
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Given List<Order> where each Order has List<Line> lines(), produce a list of distinct...": https://scrivio-interview-library.netlify.app/java/streams/6aafde76fc/