Java Streams

Stream flatMap()

March 14, 2020

The Stream flatMap() is used to flatten the stream of streams to stream of individual elements.

What is Flattening?

Flattening is like converting Collection of collection to a single collection of all those elements present in all collections.

Flattening

Consider two streams, that we want to merge into one. But we can not merge their elements by using of() method, as it will create stream of streams.

		Stream<String> a  = Stream.of("Hello ","There, ");
		Stream<String> b = Stream.of("Learning ", "Java ? ");

		//Stream<String> s = Stream.of(a,b);   error!
                Stream<Stream<String>> streamOfStreams = Stream.of(a,b);

To get just a stream of elements combined from these streams, we have to flatten the individual Streams. For this, Stream flatMap() method is used.

Syntax:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

flatMap() takes a function and returns a flattened stream. And the function it takes is also bound to return a stream, unlike the map operation in which the mapper function returns something but and map creates the stream of those returned values.

public class FlatMapOperation {

		Stream<String> a  = Stream.of("Hello ","There, ");
		Stream<String> b = Stream.of("Learning ", "Java ? ");

		Stream<String> flattened = Stream.of(a,b)
			.flatMap(e -> e)
		
		flattened.forEach(System.out::println);

}
//Output
Hello
There, 
Learning 
Java ? 

Explanation: When Stream.of(a,b) gets invoked it creates a stream of streams having [“Hello “, “There, “] as the first element and [“Learning “, “Java ? “] as the second. Later when the intermediate operation flatMap(e -> e) executes, it maps each element to itself as we passed identity function (e -> e). It returns the flattened stream of individual string.

There is a static identity method in function class ‘Function.identity()‘ which can be passed to flatMap() method as identity function.

It will take the element from the stream (which is actually the outer stream) and return the same by itself.

           Stream<String> flattenedStream = Stream.of(a,b)
			.flatMap(Function.identity());

Stream flatMap() method is very helpful when one element of the stream itself returns a Stream, and we want a combined stream of all returned the Streams.

flatMap()