Java 8 flatMap examples

We would be looking at flatMap method in Java 8 streams and Optional. In our last tutorial we looked at map method in Java 8 stream example. Let us start with the examples

1. Flatten a List<List<String>> to List<String> using flatMap

Here we have two lists, a list of front-end languages and a list of back-end languages.  And a wrapper list holds both of these lists. And we would like have the contents of both these lists in one single list.

2. Flatten Map<String, List<String>> to List<String>

Here we have a list of languages grouped by a keyword like “frontend” and “backend”. So we would be flattening the map data to a list.

3. Flatten Map<?, Map<?, List<String>>> to List<String>

Here we would be flattening a map of map. We would be using flatMap twice to flatten the data.

4. FlatMap in Optional

In Optional, flatMap can be used to process an intermediate result. Here are the Javadocs of flatMap in Optional.

If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.

Th Javadocs explain is pretty well, if a value is present, only then the mapping function is called. If the value is not present then the mapping funtion would not be invoked at all.

5. flatMapToInt

Let’s also see an example of flatMapToInt . In the below example we have a primitive int type array. And we would like to have a sum of all the integers within the array. So we would use flatMapToInt to get IntStream and use the sum operation of IntStream.



We looked at various types of data that we can flatten with the help of flatMap method provided by the Java 8 streams. I hope that you have also found them helpful. Please share in comments if you see any other interesting ways of using flatMap.

Leave a Reply