Difference between map and flatMap in java

Previous
Next

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 String and you want to make them uppercase, in this case, you can simply use map function as below.

When you run above program, you will get below output:

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

When you run above program, you will get below output:

Tianjin
Thimphu

That’s all about the difference between map and flatMap in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog