Difference Between map() and flatMap() in Java

In this post, we will discuss the difference between map() and flatMap() methods of Stream class in Java.


1. Signature

The prototype of Stream.map() is:

* @param The element type of the new stream
* @param mapper a non-interfering, stateless function to apply to each element
* @return the new stream

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

The prototype of Stream.flatMap() is:

* @param The element type of the new stream
* @param mapper a non-interfering, stateless function to apply to each
*                      element which produces a stream of new values
* @return the new stream

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


2. Definition

Both map() and flatMap() takes a mapping function which is applied to each element of a Stream<T>, and returns a Stream<R>. The only difference is that the mapping function in the case of flatMap() produces a stream of new values, whereas for map() it produces a single value for each input element.

Arrays.stream(), List.stream(), etc, are commonly used mapping function for flatMap(). Since the mapping function for flatMap() returns another stream, we should get a stream of streams. However, flatMap() has the effect of replacing each generated stream by the contents of that stream. In other words, all the separate streams that are generated by the function get flattened into one single stream.[1]


3. How to use map()

Since map() produce a Stream consisting of the results of applying the given function to the elements of the input Stream, it is often used for converting Stream of one type to Stream of another type. For instance, here’s how we can convert List of Character to List of Integer (assuming valid input).

Above code can be further shortened with lambdas as shown below:

Here’s how we can convert List of Integer to a List of Character.

This can also be done with a single call to map() function as shown below:


4. Why do we need flatMap()?

Suppose we have a List of List<Integers> and we need a single List of Integer containing elements of all the member lists. This can be done as follows:


Download   Run Code


Before flattening : [[1, 2, 3], [4, 5], [6, 7, 8]]
After flattening : [1, 2, 3, 4, 5, 6, 7, 8]


1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of