Flatmap Vs Map

By | | Updated : 2021-03-12 | Viewed : 668 times

Flatmap Vs Map

In this current tutorial, we will learn the differences between FlatMap vs. Map in Java 8 streams. You might be aware of these two important operations in Java 8 operation to map all elements with a new stream to get the required result. Both map() and flatMap() are available in Java 8 streams. Even though FlatMap and Map are used for mapping in streams, there are some differences in usage.

map() and faltMap() in java 8

Here we will be focusing on both methods for transforming into another item in each iteration for getting the required list or set in java 8 Streams.

Map (): In streams, map() performs a functional operation using the mapper function to produce a new stream for each element. Finally, map() transform all the streams into a single stream to provide the result. So this way, each element of the stream is transformed into a new result stream.

map() example in java8
List colors = Arrays.asList("red", "blue", "green", "yellow", "white", "back")

See the above given an example for a map of the stream. Here we can create a resulting stream using the map(). In each iteration, map() creates a separate stream with the result by executing the mapper function. At last, map() converts all streams into a single stream.

How does map() work?

Here each map() creates a new stream with uppercased color string and then finally all the intermediate streams transformed as new streams to provide a single list of uppercased color lists.

flatMap(): In java Streams, flatMap() method applies operation as a mapper function and provides streams of element values. Means in each iteration of each element map() creates a separate new stream. So it should be merged as a single resulted list. For that, it is required only one stream. So flatting is the mechanism to merge all intermediate streams into a single resulted stream.

How does flatMap() work?

flatMap() in java8
List colors = Stream.of(Arrays.asList("red", "blue", "green","yellow"), Arrays.asList("yellow", "white", "back","green"))

We can use the flatMap() method on a stream with the mapper function List::stream. As you know, all the intermediate operations are lazy. When Streams terminal operation executes, then each element of flatMap() provides a separate stream. In the final stage, flatMap() transforms all the streams into a new resulting stream. If you observe the resulting streams, it does not contain duplicate color values. Please execute the above-given program to understand clearly.

java Map vs. FlatMap

By observing the above working mechanism, you might be aware. flatMap() is for mapping and flatting the results where mapping and flatting are required for all elements using the mapper function. But map() will handle the mapping only.

Leave A Reply