Table of contents
1.
What is Java flatMap?
2.
How does Java flatMap() work?
3.
Java flatMap() Example
4.
flatMap() v/s map()
5.
Frequently Asked Questions
5.1.
What is meant by flatMap() in Java?
5.2.
What distinguishes a Java map() from a Java flatMap()?
5.3.
What internal processes does a Java flatMap have?
5.4.
What is meant by flatMap array?
5.5.
Where can we use flatMap and map?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

flatMap() Method in Java

Author Rashi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

What is Java flatMap?

The Java flatMap() returns a stream that contains the contents of a mapped stream. It is created by applying the mapping function to each element of the original stream. An intermediary operation is stream flatMap(Function mapper). These processes are always time-taking. A Stream instance as the input will be used for intermediate operations.And, it will return a Stream instance as output once they have completed processing.

Java flatMap

The syntax to use Java flatMap() is given below:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

In the above code R is the new stream's element type. An interface is a stream, and the type of stream element is T. A stateless function called mapper is applied to each element and returns a new stream.

Also read, Duck Number in Java and  Hashcode Method in Java

How does Java flatMap() work?

The process of flattening involves merging multiple lists of lists into a single list that contains every element from all the original lists. 

As was already mentioned in the post, Java flatMap() combines the map and flat operations, applying the map function first and then flattening the outcome. Following are the examples for how flattening happens:
 

  • Consider the following lists of lists of integers:
     

Before Flattening: [[6, 0, 5, 8], [0, 41, 7, 1], [4, 39], [72, 16, 9, 0, 7], [2]]

After Flattening: [6, 0, 5, 8, 0, 41, 7, 1, 4, 39, 72, 16, 9, 0, 7, 2]
 

  • Consider the following lists of lists of charcters:
     

Before Flatenning: [ ["C", "O", "D"], ["I", "N", "G"], ["N", "I", "N"], ["J", "A"], ["S"] ]

After Flatenning: ["C", "O", "D", "I", "N", "G", "N", "I", "N", "J", "A", "S"]
 

In a nutshell, we can say that after flattening, the Stream of <<Data Type>> is returned if there was a Stream of List of <<Data Type>> before flattening.

Also see,  Swap Function in Java

Java flatMap() Example

Code:

import java.util.*;
import java.util.stream.Collectors;
  
public class CodingNinjas
{   
    public static void main(String[] args)
    {   
        // Create a list of Prime Numbers
        List<Integer> PNum = Arrays.asList(5, 7, 11,13);
          
        // Create a list of Odd Numbers
        List<Integer> ONum = Arrays.asList(1, 3, 5);
          
        // Create a list of Even Numbers
        List<Integer> ENum = Arrays.asList(2, 4, 6, 8);
  
        List<List<Integer>> combo1 =
                Arrays.asList(PNum, ONum, ENum);
  
        System.out.println("The original list: " + combo1);
          
        // Using Java flatMap to transform and to flat
        List<Integer> combo2 = combo1.stream()
                                    .flatMap(list -> list.stream())
                                    .collect(Collectors.toList());


        // Print the list  
        System.out.println("The flattened list is: " + combo2);
    }
}
You can also try this code with Online Java Compiler
Run Code

Output:

Output

Compile and run on online java compiler.

flatMap() v/s map()

A Stream is transformed into another Stream by the function map(). Every stream element is subject to a function, and the results get stored in a new stream. The stream is not made flat by it. Also map() is only used for transformation. However, flatMap() combines a map with a flat operation, meaning it applies a function to elements and flattens them. It is also used for transformation and flattening.

For more differences, refer to the table below.

Java flatMap()

Java map()

It handles the values of the stream.

It handles the values stream.

In addition to flattening, it also implements mapping.

It only implements mapping.

Data is converted from Stream> to Stream.

Data is converted from Stream to Stream.

It utilizes One-To-Many mapping.

It utilizes One-To-One mapping.

For every input value, its mapper function creates multiple values (a stream of values).

For every input value, its mapper function generates a single value.

Whenever the mapper function returns multiple values for every input value, use the flatMap() method.

Whenever the mapper function returns a single value for each input value, use the map() method.

Frequently Asked Questions

What is meant by flatMap() in Java?

A list of element values is provided by the Java flatMap() method, which uses execution as a mapper function.

What distinguishes a Java map() from a Java flatMap()?

In comparison to flatMap(), which generates an arbitrary figure (zero or more) of values for every input value, map() produces one output value for every input value.

What internal processes does a Java flatMap have?

The result is flattened before being returned, saving you from having to do it yourself. Firstly, it applies the function returning some other Optional to the object inside.

What is meant by flatMap array?

The Java built-in function array flatMap() is utilized to flatten the elements of the given array into a new array.

Where can we use flatMap and map?

map() and flatMap() are two functions that can be utilized for transformation and mapping processes.

Conclusion

We have briefly discussed Java flatMap(), and map() , and the differences between both functions. We have also discussed how flatMap() internally works. After going through the entire article, we hope you got a more precise grasp of the topic. You can learn the basics of Java and data structures and algorithms in Java on Coding Ninjas.

Recommended Readings:


You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass