Java Stream flatMap() With Examples

Java Stream flatMap() is a very useful function to flatten the Stream after applying the given function to all the elements of the stream.

Java Stream flatMap

Let’s look at the syntax of Stream flatMap() function.

In simple words, flatMap() is used when we have a stream of collections and we want to flatten it rather than using map() function and getting the nested Stream.

Let’s look at an example to better understand this scenario. Suppose we have few List of Strings:

Now we want to merge these lists and get a new list of Strings and change the letters to uppercase. Since we have multiple lists, we will have to first merge them to a single list and then apply map() function. Something like below code:

Obviously this is a lot of rework and we have to manually merge the lists to get a single list of elements and then apply map() function. This is where flatMap() is very useful. Let’s see how we can use flatMap() to perform the same operation.

Now it’s clear that we used flatMap() function to flatten the Stream of Lists to Stream of elements.

Java Stream flatMap() Real Life Example

Let’s look into a real life example where flatMap() function will be really helpful. Suppose we have a State class that contains list of cities. Now we have a list of States and we want to get the list of all the cities. Here flatMap() will be very helpful as we won’t have to write nested for loops and iterate over the lists manually. Below is a complete example to show this scenario.

It’s very clear that flatMap() is very useful when we have to work with List of lists.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: