Map Vs FlatMap
In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.
Output:
List of fruit-[Apple, mango, pineapple, kiwi]
List generated by map-[5, 5, 9, 4]
// Java program using flatMap() function
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Test{
public static void main(String[] args)
{
// making the arraylist object of List of Integer
List<List<Integer> > number = new ArrayList<>();
// adding the elements to number arraylist
number.add(Arrays.asList(1, 2));
number.add(Arrays.asList(3, 4));
number.add(Arrays.asList(5, 6));
number.add(Arrays.asList(7, 8));
System.out.println("List of list-" + number);
// using flatmap() to flatten this list
List<Integer> flatList = number.stream().flatMap(list -> list.stream())
.collect(Collectors.toList());
// printing the list
System.out.println("List generate by flatMap-" + flatList);
}
}
Output
List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]
List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]
Comments
Post a Comment