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

• Thanks Suman for the suggestion, will update it

• It seems like u haven’t updated yet

• This is corrected now, sorry for the late response.
{"ft_lang_label":"__label__en","ft_lang_prob":0.80607146,"math_prob":0.83482105,"size":4012,"snap":"2022-40-2023-06","text_gpt3_token_len":900,"char_repetition_ratio":0.13473053,"word_repetition_ratio":0.029457364,"special_character_ratio":0.23255235,"punctuation_ratio":0.14655173,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97449553,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12],"im_url_duplicate_count":[null,null,null,null,null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-01-30T15:05:11Z\",\"WARC-Record-ID\":\"<urn:uuid:e7f01ee3-1623-4585-bfdb-1e5f5ec2ffca>\",\"Content-Length\":\"190118\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:89d30a91-83c2-4c34-b1df-73eb6f815a43>\",\"WARC-Concurrent-To\":\"<urn:uuid:c45a4207-1118-4005-af30-4303cd0ca3b1>\",\"WARC-IP-Address\":\"104.21.25.73\",\"WARC-Target-URI\":\"https://www.javadevjournal.com/java/java-difference-between-map-and-flatmap/\",\"WARC-Payload-Digest\":\"sha1:XZPFNCM2L7ERQTRUE43XYI6XQBNBNHDZ\",\"WARC-Block-Digest\":\"sha1:S3RJNRUDUWKQZCP2XKP623R7PS52RI4R\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764499819.32_warc_CC-MAIN-20230130133622-20230130163622-00633.warc.gz\"}"}