Table of contents
1.
Introduction 
2.
What is map() method? 
2.1.
For Stream
2.2.
For Optional
2.3.
Usage and Example
2.3.1.
Implementation:
2.4.
Java
2.5.
Description
3.
What is flatMap() Method?
3.1.
For Stream
3.2.
For Optional
3.3.
Usage and Example
3.3.1.
Implementation
3.4.
Java
3.5.
Description
4.
Difference Between map() and flatmap()
5.
Java Programs using map() function
5.1.
Java
6.
Java Programs using flatMap() function
6.1.
Java
7.
Frequently Asked Questions 
7.1.
Why use flatMap instead of map?
7.2.
What is the difference between map and flatMap and a good use case for each?
7.3.
What is the difference between flat map and map C++?
8.
Conclusion 
Last Updated: Jul 9, 2024
Medium

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

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

Introduction 

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.

Syntax:

For Stream

<R> Stream<R> map(Function<? super T, ? extends R> mapper)
You can also try this code with Online Java Compiler
Run Code


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

Implementation:

  • Java

Java

import java.util.*;
public class addition {
   public static void main(String[] args)
   {
       List<Integer>list=Arrays.asList(2, 5, 10, 15, 25);
       list.stream().map(number -> number + 5).forEach(System.out::println);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

7
10
15
20
30
You can also try this code with Online Java Compiler
Run Code

Description

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.

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.

Syntax:

For Stream

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
You can also try this code with Online Java Compiler
Run Code


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.

Implementation

  • Java

Java

import java.util.*; 
import java.util.stream.Collectors;
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 = ListofInts.stream() .flatMap(list -> list.stream()) .collect(Collectors.toList());
       System.out.println("After: " + listofInts);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Before: [[1, 3, 5, 7], [2, 4, 6, 8]]
After: [1, 3, 5, 7, 2, 4, 6, 8] 
You can also try this code with Online Java Compiler
Run Code

Description

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:

Parameter

map()

flatMap()

Input One value for one input is returned. Produces an output of any number of values.
Mapping one-to-one mapping (). one-to-many mapping ().
Flattening Performs the mapping only. Both mapping and flattening is done.
Stream Output is a stream of value. Create a stream of stream values.
Stream of Streams Transforms 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>.
Transformation Only transformation is done. Both transformation and mapping are done.

Java Programs using map() function

  • Java

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);
result.add(mappedItem);
}
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]
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

[1, 4, 9, 16, 25]

Java Programs using flatMap() function

  • Java

Java

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

List<String> letters = words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList());

System.out.println(letters);
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

[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.

Conclusion 

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.  

Live masterclass