Differences Between map() And flatMap() in Java 8 ?

By | June 22, 2020

In this post, we will clarify Differences Between map() And flatMap() in Java 8 using an example

Below both Methods are available in java.util.stream.Stream Interface from Java 8 onwards

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

These two methods map and flatMap can be applied to a Stream<T> and they both return a Stream<R> only. The map(Function<? super T, ? extends R> mapper) method produces one output value for each input value but flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) method produces an arbitrary number (zero or more) values for each input value.

Let’s try to understand the difference between these two methods using the below example:

Output of this Program:

——-Use of flatMap Stream to get all phones——–
999-2256-766
999-4467-788
999-5523-877
999-8766-877
999-7766-654
999-8766-754
———-Use of map Stream to get all phones———–
[999-2256-766, 999-4467-788]
[999-5523-877, 999-8766-877]
[999-7766-654, 999-8766-754]
———-Use of map stream to get all user names——-
KK
John
Sean

You May Also Like:

What are new Features added in Java 8?
When we choose LongAdder and LongAccumulator over AtomicLong & AtomicInteger ?
How can we maintain Immutability of a class with a mutable reference ?

That’s all about  Differences Between map() And flatMap() in Java 8 ?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *