Table of Contents
In this post, we will see the difference between map and flatMap in java.I have already covered Stream’s map and flatMap methodsĀ in previous articles.
As you might know, Stream’s map and flatMap method both can be applied on Stream<T> and return Stream<R> as output.
The actual difference is, map operation produces one output value for one input value but flatMap operation produces zero or more number of values for each input value.
Let’s understand with the help of the simple example.
Stream map vs flatMap
You have list of Strings and you want to make them uppercase, in this case, you can simply use map function as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog.map; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8MapExample { public static void main(String[] str) { List<String> listOfCountries=Arrays.asList("India","China","Nepal","Bhutan"); List<String> listOfCountriesUppercase=listOfCountries.stream() .map(String::toUpperCase) .collect(Collectors.toList()); listOfCountriesUppercase.forEach(System.out::println); } } |
When you run above program, you will get below output:
CHINA
NEPAL
BHUTAN
map works well in case of simple cases as above.
What if you have more complex data structure such as List of List of String(List<List<String>>)
Let’s say you have a list of list of cities(List<List<String>>) and you want to find all the cites which start with "T".
You can not directly use filter on List<List<String>>, it’s not going to work.
You need to use flatmap to flatten the List and then use the filter on it to get the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog.flatMap; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8FlatMapExample { public static void main(String[] str) { List<List<String>> listofListOfCities=Arrays.asList(Arrays.asList("Delhi","Mumbai"), Arrays.asList("Beijing","Shanghai","Tianjin"), Arrays.asList("Kathmandu","Lalitpur"), Arrays.asList("Thimphu","Phuntsholing")); List<String> listOfCitiesUppercase=listofListOfCities.stream() .flatMap(citiesByCountries -> citiesByCountries.stream()) .filter(s -> s.startsWith("T")) .collect(Collectors.toList()); listOfCitiesUppercase.forEach(System.out::println); } } |
When you run above program, you will get below output:
Thimphu
That’s all about the difference between map and flatMap in java.