The Difference Between map() and flatMap()

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.

 

Introduction

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 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.

Java flatMap

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

 

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.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of