Java 8 Stream flatMap

Java 8 Stream flatmap

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

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

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"
    package org.arpit.java2blog.flatMap;

import java.util.List;

public class Employee {

String name;
int age;
List<String> listOfCities;

public Employee(String name, int age,List<String> listOfCities) {
    super();
    this.name = name;
    this.age = age;
    this.listOfCities=listOfCities;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

public List<String> getListOfCities() {
    return listOfCities;
}

public void setListOfCities(List<String> listOfCities) {
    this.listOfCities = listOfCities;
}

}

  1. Create main class named "Java8StreamMapMain.java"
    package org.arpit.java2blog.flatMap;

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors;

public class Java8StreamMapMain {

public static void main(String args[])
{
    List<Employee> listOfEmployees = createListOfEmployees();

    Set<String> listOfCities=listOfEmployees.stream()
                                    .flatMap(e -> e.getListOfCities().stream()) 
                                    .collect(Collectors.toSet());
    listOfCities.forEach(System.out::println);
}       

public static List<Employee> createListOfEmployees()
{
    List<Employee> listOfEmployees=new ArrayList<>();
    Employee emp1= new Employee("Ankit",20,Arrays.asList("Delhi","Mumbai"));
    Employee emp2= new Employee("Shilpa",24,Arrays.asList("Kolkata","Pune"));
    Employee emp3= new Employee("Megha",20,Arrays.asList("Delhi","Patna"));
    Employee emp4= new Employee("Mohan",20,Arrays.asList("Banglore","Pune"));
    listOfEmployees.add(emp1);
    listOfEmployees.add(emp2);
    listOfEmployees.add(emp3);
    listOfEmployees.add(emp4);
    return listOfEmployees;
}

}

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.

package org.arpit.java2blog.flatMap;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8StreamFlatMapNumber {

    public static void main(String[] args)
    {
        int[][] numbers={
                {1,2},
                {3,4},
                {5,6}
        };
         //Stream<int[]>
        Stream<int[]> temp = Arrays.stream(numbers);
        List<Integer> listOfIntegers= temp
                .flatMap( x -> Arrays.stream(x).boxed())
                .map(e -> 2*e)
                .collect(Collectors.toList());

        System.out.println(listOfIntegers);

    }
}

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 Java 8 stream flatMap example.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.