Learnitweb

map() vs flatMap() in Java

map() and flatmap() methods are found in Optional class and Stream interfaces in Java 8. We’ll discuss the use of both these methods with respect to Optional and Stream.

1. flapMap() and map() methods in Optional

1.1 Syntax of map()

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

1.2 Syntax of flatMap()

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

map() method works fine when we have to work with an Optional of a certain type, like Optional<String>. But it is not very convenient to work with map() when the type is somewhat complex, like Optional<Optional<String>>. Let us understand this with an example.

Optional.of("hello").map(s -> Optional.of("HELLO")) returns Optional<Optional<String>> type response.

This is not convenient to use in comparison to Optional<String>.

In such case, we can use flatMap() to flat the result.

Optional.of("hello").flatMap(s -> Optional.of("HELLO")) returns Optional<String> type of response.

2. flatMap() and map() methods in Stream

2.1 Syntax of map()

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

2.2 Syntax of flatMap()

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

flatMap() = map() + flattening

Difference between map() and flatMap() can be understood with the help of following points:

  • flatMap is a combination of map and flat operations.
  • Function passed to map() returns a single value whereas the function you pass to the flatMap() returns a stream of values.
  • There is no flattening in case of map like flatMap.

2.3 Example of map()

import java.util.Arrays;
import java.util.List;
/*Java program to find square(n*n)
of elements of list*/ 
public class StreamMapExample {
    public static void main(String[] args) {
        //Create list of integers
      List<Integer> list = Arrays.asList(2, 3, 4, 5);
        
      //Use map() method to calculate square of elements
        // and print the result
        list.stream().map(element -> element * element).forEach(System.out::println);
    }
}

Output

4
9
16
25

2.4 Example of flatMap()

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
  
public class FlatMapExample 
{
    public static void main(String[] args) 
    {
        //nested array
      String[][] dataArray = new String[][]{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};
         
        List<String> flattedList = Arrays.stream(dataArray)     // convert array to stream 
                                    .flatMap(x -> Arrays.stream(x)) // flat the stream
                                    .collect(Collectors.toList()); // collect result
  
        System.out.println(flattedList);
    }
}

Output

[a, b, c, d, e, f, g, h, i]