The flatMap
function defined in the Stream
class is used to combine or merge multiple maps
and apply the flat
operations. It's an Intermediate
function. it's majorly used for flating
Collection
of Collection
or Stream
of Stream
to merge everything into a single result Stream
package org.wesome.java8;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
class Apple {
public static void main(String args[]) {
List<Integer> listA = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> listB = Arrays.asList(6, 7, 8, 9, 10);
List<Integer> listC = Arrays.asList(11, 12, 13, 14, 15);
List<List<Integer>> list = Arrays.asList(listA, listB, listC);
System.out.println("list = " + list);
System.out.println("*---------------------------flatMap on List of Integers---------------------------*");
List<Integer> flatMapInteger = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println("flatMapInteger = " + flatMapInteger);
System.out.println("*---------------------------flatMap on List of Integers with Map---------------------------*");
List<Integer> flatMapAndMapInteger = list.stream().flatMap(Collection::stream).map(integer -> integer + 1).collect(Collectors.toList());
System.out.println("flatMapAndMapInteger = " + flatMapAndMapInteger);
System.out.println("*---------------------------flatMap on list of Strings---------------------------*");
String[][] fruits = new String[][]{{"Apple", "Macintosh"}, {"Orange", "Valencia"}, {"Mango", "Alphonso"}, {"Avocado", "Hass"}};
List<String> flatMapString = Arrays.stream(fruits).flatMap(Arrays::stream).collect(Collectors.toList());
System.out.println("flatMapString = " + flatMapString);
}
}