Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Last Updated: Jul 9, 2024

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

Table of contents
Learn to use AI Tools & ChatGPT to excel as Microsoft SDE
11 Jul, 2024 @ 01:30 PM
Pranav Malik
SDE 2 @


Java is essentially an object-oriented language but has numerous functional programming techniques. Processing collections of objects is done using the Stream API was first introduced in Java 8. A stream is a collection of objects that supports several different operations and that may be pipelined to create the desired outcome. 

Streams convey the outcome of the pipelined techniques; they do not alter the underlying data structure.

The stream is marked by terminal operations, which also yield the outcome.

Difference between map and flatmap


Functional programming gave rise to the functions map() and flatMap() and in this blog, we will look at the difference between map() and flatmap().

Also see, Longest Common Substring and Rabin Karp Algorithm

What is map() method? 

A stream that contains the output of applying the specified function to each element of this stream is returned by the stream map function. A Stream instance is used as input by intermediate operations, which are then used to process another Stream object and return a new Stream instance.


For Stream

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

Here, R is the newly created stream's element type. Interface T is a stream, and stream components of type T are streams. When applied to each element, the stateless function known as a "mapper" creates a new stream and returns it.

When we need to map the components of a sure collection to a specific function and subsequently need to return the stream with the updated results, we may use this method, which is a difference between map() and flatmap().

Read More About, Data Structures and Algorithms

For Optional

public <U> Optional<U> map(Function<? super T, ? extends U> mapper)

The map() function can also be used with the Optional class in Java, which is a container object that may or may not contain a non-null value. The map() function on Optional applies a given function to the value in the Optional if it's present and returns a new Optional containing the result of the transformation. If the original Optional is empty, the map() function returns an empty Optional.

Usage and Example

Stream map() function with the operation of number + 5 on each element of the stream


  • Java


import java.util.*;
public class addition {
   public static void main(String[] args)
       List<Integer>list=Arrays.asList(2, 5, 10, 15, 25); -> number + 5).forEach(System.out::println);





This Java code defines a class named addition with a main method that performs the following operations:

  1. Creates a List<Integer> using the Arrays.asList() method and initializes it with the integers 2, 5, 10, 15, and 25.
  2. Calls the stream() method on the List object to create a stream of its elements.
  3. Calls the map() method on the stream and passes in a lambda expression as an argument. The lambda expression takes each element in the stream and adds 5 to it, returning the result as a new element.
  4. Calls the forEach() method on the resulting stream, passing in a method reference System.out::println. This will print each element of the stream to the console.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job

What is flatMap() Method?

The stream flatMap function returns a stream containing the contents of a mapped stream formed by applying a mapping function to each element in the original stream.

Upon placing its contents into this stream, each mapped stream is shut down. A stream that contains nothing is utilized in its place if a mapped stream is null.


For Stream

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

Since we can't flatten our string using a map, we may use flatMap() when we need to flatten or change the string () which is a prominent difference between map() and flatmap(). 

flatMap() = map() + Flattening. A flatMap() combines two operations; transformation and flattening of a stream of values into another stream that only consists of a single list storing values.

For Optional

public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)

The flatMap() function on Optional applies a given function to the value in the Optional if it's present, and returns a new Optional that is the result of the flattened stream. If the original Optional is empty, the flatMap() function returns an empty Optional.

Usage and Example

Getting the 1st character of all the strings present in a list of strings and returning the result in the form of a stream.


  • Java


import java.util.*; 
public class main
   public static void main(String[] args)
       List<Integer> Number1 = Arrays.asList(1, 3, 5, 7);
       List<Integer> Number2 = Arrays.asList(2, 4, 6, 8);
       List<List<Integer>> ListofInts = Arrays.asList(Number1, Number2);
       System.out.println("Before: " + ListofInts);
       List<Integer> listofInts = .flatMap(list -> .collect(Collectors.toList());
       System.out.println("After: " + listofInts);



Before: [[1, 3, 5, 7], [2, 4, 6, 8]]
After: [1, 3, 5, 7, 2, 4, 6, 8] 


This Java code demonstrates how to use the flatMap() method of the Stream class to convert a list of lists into a single list.

First, two lists of integers are created using the Arrays.asList() method. These lists are then stored in another list called ListofInts, which is a list of lists.

Next, the flatMap() method is called on ListofInts. This method flattens the list of lists into a single stream of integers by first calling the stream() method on each list in ListofInts, and then flattening the resulting streams into a single stream of integers. The resulting stream is then collected into a list using the Collectors.toList() method.

Finally, the original ListofInts and the flattened list listofInts are printed to the console.

Also see, Morris Traversal for Inorder.

Difference Between map() and flatmap()

The Difference between map() and flatmap() can be stated as follows:




InputOne value for one input is returned.Produces an output of any number of values.
Mappingone-to-one mapping ().one-to-many mapping ().
FlatteningPerforms the mapping only.Both mapping and flattening is done.
StreamOutput is a stream of value.Create a stream of stream values.
Stream of StreamsTransforms Stream<T> to Stream<R> or Optional<T> to Optional<R>.It performs the map functionality as well as converts Stream<Stream<T>> to Stream<T> or Optional<Optional<T>>to Optional<T>.
TransformationOnly transformation is done.Both transformation and mapping are done.

Java Programs using map() function

  • Java


import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class MapExample {
public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) {
List<R> result = new ArrayList<>(list.size());
for (T item : list) {
R mappedItem = mapper.apply(item);
return result;

public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = map(numbers, x -> x * x);
System.out.println(squaredNumbers); // prints [1, 4, 9, 16, 25]


[1, 4, 9, 16, 25]

Java Programs using flatMap() function

  • Java


import java.util.Arrays;
import java.util.List;

public class FlatMapExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("Hello", "World");

List<String> letters =
.flatMap(word ->"")))



[H, e, l, l, o, W, o, r, l, d]

Frequently Asked Questions 

Why use flatMap instead of map?

The flatMap() function is used instead of map() when the transformation applied to each element of a collection returns another collection, and we want to flatten the resulting collection of collections into a single collection. 

What is the difference between map and flatMap and a good use case for each?

`map` transforms each element in a stream into another form individually, while `flatMap` transforms each element into a stream and flattens the result. Use `map` for one-to-one transformations and `flatMap` for one-to-many transformations, such as flattening nested collections.

What is the difference between flat map and map C++?

In C++, the map function applies a given function to each element in a collection and returns a new collection of the same size. In contrast, the flat_map function first applies a function to each element in a collection, then flattens the resulting nested collections into a single stream.


In this blog, we have discussed the difference between flatmap and map functions with some examples to understand their workings.

If you think this blog has helped you enhance your knowledge about the above question, and if you want to learn more, check out our articles:

Recommended Readings:

1. Difference Between Hashmap And Linkedhashmap
2. Difference between HashMap and TreeMap

3. logic for programming

4 Internal Working of HashMap 

5. Difference Between IOT and M2M


And many more on our website.

Refer to our Guided Paths on Coding Ninjas Studio to learn more about DSACompetitive ProgrammingC++, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Previous article
How to fix: "RangeError: Maximum call stack size exceeded"
Next article
What is the Difference Between String and Character?