|
|
Java 8 Stream flatMap
Author: Venkata Sudhakar
The flatMap operation in Java 8 Streams solves the problem of nested collections. When you have a List of Lists, or a List of objects where each object contains a List, a regular map() gives you a Stream of Streams. flatMap() instead flattens everything into a single Stream. The name is descriptive: it maps each element to a Stream, then flats all those streams into one. The difference between map and flatMap is simple: map returns one output element for each input element (one-to-one), while flatMap returns zero or more output elements for each input element (one-to-many). A common use case is extracting all items across a list of orders, all words across a list of sentences, or all tags across a list of blog posts into one flat list. The below example shows flatMap applied to three typical scenarios: flattening a list of orders into a list of all items, splitting sentences into individual words, and filtering with Optional.
It gives the following output,
All items across all orders:
Keyboard - $89.99
Mouse - $29.99
Monitor - $349.99
Headset - $59.99
Webcam - $79.99
USB Hub - $24.99
Total revenue: $634.94
Most expensive: Monitor
It gives the following output,
Unique words: 15
First 5: [Change, Kafka, Terraform, as, capture]
Present IDs: [MIG-001, MIG-002, MIG-003]
map vs flatMap at a glance: Use map when each element transforms into exactly one new element: orders.stream().map(Order::getId) gives one ID per order. Use flatMap when each element expands into zero or more elements: orders.stream().flatMap(o -> o.getItems().stream()) gives all items across all orders. A quick test: if your map lambda returns a List or Stream instead of a plain value, you almost certainly want flatMap instead.
|
|