Quick revision
The short answer
From Java 9 we write ids.stream().map(this::find).flatMap(Optional::stream).toList(): Optional.stream() returns a stream of zero or one element, so flatMap drops the empty results and unwraps the present ones. Before Java 9 we wrote .filter(Optional::isPresent).map(Optional::get), which does the same in two steps. Since Java 16, mapMulti also works: .<User>mapMulti((id, sink) -> find(id).ifPresent(sink)).
What to remember
In this answer, we saw how to turn a list of ids into the users that exist. On Java 9 and later, map(this::find).flatMap(Optional::stream).toList() does it in one pipeline, because Optional.stream() returns a stream of zero or one element and flatMap joins them, dropping the empties. On Java 8 we used filter(Optional::isPresent).map(Optional::get), and since Java 16 mapMulti with ifPresent(sink) is another option, useful mainly in hot paths.
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.
From Java 9 we write ids.stream().map(this::find).flatMap(Optional::stream).toList(): Optional.stream() returns a stream of zero or one element, so flatMap drops the empty results and unwraps the present ones. Before Java 9 we wrote .filter(Optional::isPresent).map(Optional::get), which does the same in two steps. Since Java 16, mapMulti also works: .<User>mapMulti((id, sink) -> find(id).ifPresent(sink)).
Why this question is asked
Turning a list of ids into the objects that actually exist is one of the most common small tasks in service code: load the users mentioned in a request, fetch the products in a basket, resolve references from a message. The interesting part is that the lookup returns Optional, so the stream contains a mix of empty and present results that we need to filter and unwrap. Interviewers ask this to see whether we know the idiomatic Java 9 approach and why it works. In this answer, we will set up the problem, write the Java 9 solution, see how Optional.stream() makes it work, look at the older approach and at mapMulti, and compare them.
1Setting Up the Problem
We have a list of ids and a lookup method that may not find a user. The goal is a List<User> containing only the users that exist, in the order of the ids.
If we simply map each id through find, we get a Stream<Optional<User>> with three elements: one holding Asha, one empty, one holding Ben. That is not what we want to return, so the next step must remove the empty one and take the users out of their Optionals.
2The Java 9 Approach With flatMap
The idiomatic solution uses flatMap together with Optional.stream(), a method added in Java 9.
Notice that one operation does both jobs: it removes the empty results and unwraps the present ones. toList() was added in Java 16 and returns an unmodifiable list; on Java 9 to 15, use collect(Collectors.toList()) instead. If callers need to modify the result, collect(Collectors.toCollection(ArrayList::new)) makes that explicit.
3How Optional.stream() Makes This Work
flatMap takes a function that turns each element into a stream, then joins all those streams into one. Optional.stream() returns a stream with one element when the Optional holds a value, and an empty stream when it does not. So each present user contributes one element to the joined stream, and each empty result contributes nothing.
| id | find(id) | Optional.stream() | In the result |
|---|---|---|---|
| u1 | Optional[Asha] | stream of one: Asha | Asha |
| u2 | Optional.empty | empty stream | nothing |
| u3 | Optional[Ben] | stream of one: Ben | Ben |
The idea of treating an Optional as a collection of zero or one element is what makes it fit naturally into stream pipelines, and it is the main reason Optional.stream() was added.
4The Approach Before Java 9
On Java 8, Optional has no stream() method, so we filter out the empty results first and then unwrap the rest.
This is correct, because get() is only called on Optionals that passed the isPresent filter. But it splits one idea across two steps, and it contains a get() call that static analysis tools often flag, so on Java 9 and later the flatMap version is preferred.
5The mapMulti Alternative
Java 16 added mapMulti, which gives each element a sink, a consumer that accepts zero or more output values. We can push the user into the sink only when it exists.
The type witness <User> is needed because the compiler cannot infer the output type of mapMulti from the lambda. mapMulti avoids creating a small stream per element, which can matter in very hot loops, but it is less familiar to most readers. For everyday code I would write the flatMap version and keep mapMulti for cases where profiling shows the difference matters.
6Follow-up questions
Does the order of the users match the order of the ids?
Yes. The stream is sequential and ordered because it comes from a List, and flatMap and mapMulti preserve encounter order, so the result follows the ids, skipping missing users.
What if find() can throw an exception?
Then the exception propagates out of the stream and the whole operation fails. If one bad id should not stop the rest, find should catch the failure and return Optional.empty(), or return a result type that records the error so the caller can report it.
Is calling find() once per id a performance problem?
If find hits a database, yes: three ids mean three queries. In real code we would usually load all users in one query, such as a repository's findAllById(ids), and use the stream only for ordering or mapping. The stream approach shown here is ideal when lookups are cheap, such as an in-memory cache.
7Conclusion
In this answer, we saw how to turn a list of ids into the users that exist. On Java 9 and later, map(this::find).flatMap(Optional::stream).toList() does it in one pipeline, because Optional.stream() returns a stream of zero or one element and flatMap joins them, dropping the empties. On Java 8 we used filter(Optional::isPresent).map(Optional::get), and since Java 16 mapMulti with ifPresent(sink) is another option, useful mainly in hot paths.
Open with
I'd map each id through find, which gives a stream of Optionals, and then flatMap with Optional::stream, and finish with toList. So it's ids.stream().map(this::find).flatMap(Optional::stream).toList(). The reason it works is that Optional.stream, added in Java 9, returns a stream of one element when the value is present and an empty stream when it isn't. flatMap joins those small streams, so present users come through unwrapped and the empty results simply disappear. toList is Java 16 and gives an unmodifiable list; before that I'd use collect with Collectors.toList.
Then, if they want more
On Java 8, where Optional has no stream method, I'd write filter(Optional::isPresent) followed by map(Optional::get). That's safe because get is only called after the filter, but it splits one idea into two steps and leaves a get call that linters complain about.
Since Java 16 there's also mapMulti: I'd write a mapMulti with a User type witness and a lambda that calls find(id).ifPresent(sink), so only existing users get pushed into the output. It avoids creating a tiny stream per element, but it's less familiar, so I'd keep it for hot paths.
In real code, if find hits a database, I'd also consider loading all ids in one query instead of one call per id.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9, Java 16, Java 8
- 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<String> ids and a method Optional<User> find(String id), get a list of the...": https://scrivio-interview-library.netlify.app/java/optional/df9d0d22a7/