flatmap
About
In Java streams, flatMap
is an intermediate operation, meaning it returns a new stream without modifying the original, and combines two actions:
Mapping: It applies a function (a
Function
interface implementation) to each element in the stream, producing a new stream of corresponding elements.Flattening: It merges the resulting nested streams (created by the mapping) into a single, flat stream.
flatMap
is particularly useful for working with collections that contain nested structures. It works with streams of any type, allowing for flexibility in data processing.
Examples
Example 1: We have a list of list of integers. Our task in to return a list of integers having numbers divisible by 2.
Traditional approach using iteration
Using Streams and flatMap
Example 2: Lets say we have a list of sentences. Our task is to extract all unique words from sentences.
Example 3: Lets say we have a list of sentences. Our task is to extract all unique words from sentences and the associated length of the word in Map.
Last updated
Was this helpful?