Difference Between map() And flatMap() In Java Stream - GeeksforGeeks

03 Mar, 2021
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.
The Syntax of the map() is represented as:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
The Syntax of the flatMap() is represented as:-
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Where R is the element type of the new stream. The stream is an interface and T is the type of stream elements and mapper is a stateless function that is applied to each element and the function returns the new stream.
map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results.
Example: Multiplying All the elements of the list by 3 and returning the updated list.
flatMap() can be used where we have to flatten or transform out the string, as we cannot flatten our string using map().
Example: Getting the 1st Character of all the String present in a List of Strings and returning the result in form of a stream.
Difference Between map() and flatmap()
Below are the Java Programs using map() function:
Java
// Java program using map() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG {        public static void main(String[] args)    {        // making the array list object        ArrayList<String> fruit = new ArrayList<>();        fruit.add("Apple");        fruit.add("mango");        fruit.add("pineapple");        fruit.add("kiwi");        System.out.println("List of fruit-" + fruit);                // lets use map() to convert list of fruit        List list = fruit.stream()                        .map(s -> s.length())                        .collect(Collectors.toList());        System.out.println("List generated by map-" + list);    }}
Output:
List of fruit-[Apple, mango, pineapple, kiwi]
List generated by map-[5, 5, 9, 4]
Below is the Java Program using flatMap():
Java
// Java program using flatMap() functionimport java.io.*;import java.util.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;class GFG {    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);    }}
List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]
List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]

java-stream
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples