flatMap
An operation that turns each element into a stream, or an Optional, and joins the results into one flat stream, removing a level of nesting.
In more detail
On a stream of lists, flatMap(List::stream) produces one stream of all the inner elements. On Optional, flatMap is used when the transformation itself returns an Optional, so you do not end up with an Optional inside an Optional.
Example
groups.stream().flatMap(List::stream)Related terms
- intermediate operation — A stream step, such as filter, map, sorted or distinct, that returns another stream and does no work until a terminal operation runs.
- Optional — A container that holds either one value or nothing, used as a return type to make "no result" visible to the caller.
Taught in
- Advanced Stream Operations — Modern Java: Virtual Threads & High-Throughput Services
- Handling Nulls With Optional — Modern Java: Virtual Threads & High-Throughput Services
- Stream Pipelines, Primitive Streams And Optional — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep