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
Functioninterface 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.
// Input
List<List<Integer>> list = List.of(
List.of(1,2,3,14,17),
List.of(4,5,6,18),
List.of(7,8,9),
List.of(10,11,12,13)
);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