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
1 2 3 |
<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.
- Create a class named "Employee.java"
12345678910111213141516171819202122232425262728293031323334353637package org.arpit.java2blog.flatMap;</li></ol><p>import java.util.List;</p><p>public class Employee {</p><pre><code>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;}}
- Create main class named "Java8StreamMapMain.java"
123456789101112131415161718192021222324252627282930313233package org.arpit.java2blog.flatMap;</li></ol><p>import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Set;import java.util.stream.Collectors;</p><p>public class Java8StreamMapMain {</p><pre><code>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
MumbaiAnother example
Let’s say you have 2D array of integers and you need to create a flattened list of integers after doubling each element.
123456789101112131415161718192021222324252627282930package 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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
- Create main class named "Java8StreamMapMain.java"