Java 8 Stream flatMap

Previous
Next

In this post, we will see about Java 8 Stream flatMap function.Before understanding flatMap, you should go through stream’s map function

Stream’s flatMap method takes single element from input stream and produces any number of output values and flattens result to output stream.When you apply flatMap function on each of element of the stream, it results in stream of values rather than single value as in case of Stream’s map function.

Java 8 Stream flatMap function

As per java docs, Stream’s flatMap returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

Confused? Don’t worry, example will make it very clear.
Function is a functional interface available in Java 8 java.util.function.Function accepts one input and produce a result.
Let’s understand with the help of a simple example.

Java 8 Stream flatMap example

Let’s say you have an employee class. Each employee has list of cities where they have lived in past.You need to find list of all cities where Employees have lived in.

For example:
Let’s say Ramesh has lived in Delhi, Mumbai and Rekha has lived in Pune, Delhi, then the output will be Delhi, Mumbai, Pune.

So we will use flatMap function to map each employee to list of cites to flatten it and then collection it in form of set.

1. Create a class named “Employee.java”

2. Create main class named “Java8StreamMapMain.java”

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

Delhi
Patna
Banglore
Kolkata
Pune
Mumbai

Another example

Let’s say you have 2D array of integers and you need to create a flattened list of integers after doubling each element.

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

[2, 4, 6, 8, 10, 12]

If you notice, we have used flatMap to flatten the 2D array and then used map function to double of input number in above example.

That’s all about Java 8 Stream flatMap example.

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