Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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()

                                        map()                                            flatMap()
The function passed to map() operation returns a single value for a single input. The function you pass to flatmap() operation returns an arbitrary number of values as the output.
One-to-one mapping occurs in map(). One-to-many mapping occurs in flatMap().
Only perform the mapping. Perform mapping as well as flattening.
Produce a stream of value. Produce a stream of stream value.
map() is used only for transformation. flatMap() is used both for transformation and mapping.

Below are the Java Programs using map() function:

Java




// Java program using map() function
import 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() function
import 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);
    }
}


Output

List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]
List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]


Last Updated : 14 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads