Difference Between map and flatMap in Java

In this article, we will look at the difference between map and flatMap in Java. Java 8 stream API provides map() and flatMap() method. Both these methods are intermediate methods and returns another stream as part of the output. Let’s see what is the main difference between map and flatMap() in Java 8.

 

Difference between map and flatMap in Java

The main difference between the map and flatMap is the return type. Both produce Stream<R>. The map produces one output value for each input value where flatMap provides one or more values for each input value. To put it in simple words, a map is for transformation while flatMap is a combination of transformation and flattering.

flatMap() = map() + Flattening.

 

1. Map Function

The map() method with Stream API takes a function as an argument. It applies the function on every element and mapping it to a new element. Let’s take an example where we want to return the number of characters for each word in a list. To do this, we need to apply the function to each element of the list. This function job is to accept the word and return the length of the work.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {

    public static void main(String[] args) {
        List words= Arrays.asList("Java Dev Journal","Java", "Spring Boot","Java 8");

        List wordCount = words.stream()
                        .map(String::length)
                        .collect(Collectors.toList());

        wordCount.forEach(System.out::println);
    }
}

When we run this program, we will have the following output

16
4
11
6

In this code, we passed String::length method reference to the map function to return the word count for each word.

 

2. Why Need Java flatMap()?

To understand why we need flatMap() and what is the difference between map and flatMap in Java, let’s extend out previous example. Let’s try to return a list of unique words for the input:

List words= Arrays.asList("JavaDevJournal","Java");

For this input, we are looking for the following output.[J, a, v, D, e, o, u, r, n, l]. How would you approach this situation? Let’s see what will be the output if we try below code

List words= Arrays.asList("JavaDevJournal","Java");
words.stream().map( s-> s.split("")).distinct().collect(Collectors.toList());

There is one issue with above approach, our map() method returns String[] for each word. The final output of our map() method is Stream<String> and the output of the entire statement will be List<String[]>. This is how the transformation look like

 

Java 8 map

We were looking for a list of unique words but ended up getting a List<String[]>(List of String array). To handle similar use cases, we need the flatMap() function. The flatMap() will map flat the input in to a single stream.Let’s change our code to see flatMap in action:

List < String > words = Arrays.asList("JavaDevJournal", "Java");
List < String > unique = words.stream()
 .map(s -> s.split(""))
 .flatMap(Arrays::stream)
 .distinct()
 .collect(Collectors.toList());

Let’s see how the flatMap function works while transforming the content.

Difference Between map and flatMap in Java

 

Out flatMap function will concatenates all the input stream in to a single stream.

 

3. Video Description

In case you are more interested in the visual description, I have also published video on my YouTube channel which provided more in depth details about the difference between map and flatMap in Java and when and where we should use it.

Summary

In this post, we saw the difference between map and flatMap in Java. We learned when to use map vs flatMap in Java8. The source code for this post is available on the GitHub.

4 thoughts on “Difference Between map and flatMap in Java”

  1. Good effort to explain but one little correction is required. What I see, in second example after distinct operation stream contains ‘J’ once but in your picture ‘J’ is twice (1st and 6th). If you modify the picture then there would be no confusion.

Comments are closed.