Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


1. Overview

map() and flatMap() APIs stem from functional languages. In Java 8, you can find them in Optional, Stream and in CompletableFuture (although under slightly different name).

Streams represent a sequence of objects, whereas optionals are classes that represent a value that can be present or absent. Among other aggregate operations, we have the map() and flatMap() methods.

Despite the fact that both have the same return types, they are quite different. Let's explain these differences by analyzing some examples of streams and optionals.

Further reading:

Iterate over a Map in Java

Learn different ways of iterating through the entries of a Map in Java.

Map Serialization and Deserialization with Jackson

A quick and practical guide to serializing and deserializing Java Maps using Jackson.

How to Store Duplicate Keys in a Map in Java?

A quick and practical guide to handling duplicate keys by using multimaps in Java.

2. Map and Flatmap in Optionals

The map() method works well with Optional – if the function returns the exact type we need:

Optional<String> s = Optional.of("test");

However, in more complex cases we might be given a function that returns an Optional too. In such cases using map() would lead to a nested structure, as the map() implementation does an additional wrapping internally.

Let's see another example to get a better understanding of this situation:

  .map(s -> Optional.of("STRING")));

As we can see, we end up with the nested structure Optional<Optional<String>>. Although it works, it's pretty cumbersome to use and does not provide any additional null-safety, so it is better to keep a flat structure.

That's exactly what flatMap() helps us to do:

assertEquals(Optional.of("STRING"), Optional
  .flatMap(s -> Optional.of("STRING")));

3. Map and Flatmap in Streams

Both methods work similarly for Optional.

The map() method wraps the underlying sequence in a Stream instance, whereas the flatMap() method allows avoiding nested Stream<Stream<R>> structure.

In the following example, map() produces a Stream consisting of the results of applying the toUpperCase() method to the elements of the input Stream:

List<String> myList = Stream.of("a", "b")
assertEquals(asList("A", "B"), myList);

map() works pretty well in such a simple case, but what if we have something more complex such as a list of lists as an input.

Let's see how it works:

List<List<String>> list = Arrays.asList(

This snippet prints a list of lists [[a], [b]].
Now, let's use a flatMap():


The result of such a snippet will be flattened to [a, b].

The flatMap() method first flattens the input Stream of Streams to a Stream of Strings (for more about flattening, see the article). Thereafter it works similarly to the map() method.

4. Conclusion

Java 8 gives us the opportunity to use the map() and flatMap() methods that originally were used in functional languages.

We can invoke them on Streams and Optionals. These methods help us to get mapped objects by applying the provided mapping function.

As always, you can check out the examples provided in this article over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

Inline Feedbacks
View all comments
Zsolt Horváth
Zsolt Horváth
3 years ago

Great article, just like all the others in your serie.
Minor comment, in section 3. this code doesn’t compile:

List myList = Stream.of(“a”, “b”)
assertEquals(asList(“A”, “B”), myList); -> should be assertEquals(Arrays.asList(“A”, “B”), myList);

Grzegorz Piwowarek
Grzegorz Piwowarek
3 years ago
Reply to  Zsolt Horváth

Zsolt, static import of asList is assumed there in order to shorten the actual code in the article

Comments are closed on this article!