Stream flatMap() in Java with examples
Note : Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead.
flatMap() V/s map()
1) map() takes a Stream and transform it to another Stream. It applies a function on each element of Stream and store return value into new Stream. It does not flatten the stream. But flatMap() is the combination of a map and a flat operation i.e, it applies a function to elements as well as flatten them.
2) map() is used for transformation only, but flatMap() is used for both transformation and flattening.
Syntax :
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
where, R is the element type of the new stream. Stream is an interface and T is the type of stream elements. mapper is a stateless function which is applied to each element and the function returns the new stream.
Example 1 : flatMap() function with provided mapping function.
Output :
5.6 7.4 4 1 2.3
Example 2 : flatMap() function with provided operation of mapping string with character at position 2.
Output :
e G e g
How does flatMap() work ?
As already discussed in the post that flatMap() is the combination of a map and a flat operation i.e, it first applies map function and than flattens the result. Let us consider some examples to understand what exactly flattening a stream is.
Example 1 :
The list before flattening :
[ [2, 3, 5], [7, 11, 13], [17, 19, 23] ]
The list has 2 levels and consists of 3 small lists. After Flattening, it gets transformed into “one level” structure as shown :
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
Example 2 :
The list before flattening :
[ ["G", "E", "E"], ["K", "S", "F"], ["O", "R", "G"], ["E", "E", "K", "S"] ]
The list has 3 levels and consists of 4 small lists. After Flattening, it gets transformed into “one level” structure as shown :
["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"]
In short, we can say that if there is a Stream of List of <<Data Type>> before flattening, then on applying flatMap(), Stream of <<Data Type>> is returned after flattening.
Application :
Output :
The Structure before flattening is : [[5, 7, 11, 13], [1, 3, 5], [2, 4, 6, 8]] The Structure after flattening is : [5, 7, 11, 13, 1, 3, 5, 2, 4, 6, 8]
Comments
Post a Comment