Skip to content

Optional.map vs Optional.flatMap

Low Jun Kai, Sean edited this page Nov 30, 2020 · 1 revision

Original Discussion Link

Optional Javadocs API: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html

Description

I personally felt that the descriptions are pretty cryptic and hard to understand, so much so that it was easier for me to understand by reading OpenJDK's source code. So I hope this ELI5 might be useful for others like me.

Official description of Optional.map:

If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.

Official description of Optional.flatMap:

If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional.

ELI5 description of Optional.map:

Let us have Optional<MyClass> myOp. myOp.map is meant to take in a function that does not return an Optional. If there is a value inside the myOp, apply the function to the value. Since we do not know if the result of the function will *chibabom or not, we wrap the result in an Optional for safety. If there is no value inside the myOp, we return and empty Optional.

ELI5 description of Optional.flatMap:

Let us have Optional<MyClass> myOp. myOp.flatMap is meant to take in a function that already returns an Optional. As a matter of fact, it will not compile if the mapper function does not return an Optional. If there is a value inside the myOp, apply the function to the value. Since we know that the function already returns an Optional, there is no fear that it will *chibabom. Therefore wrapping the result in another Optional is redundant, and we can return it directly. If there is no value inside the myOp, we return and empty Optional.

*chibabom = explode, 爆炸, null value, invalid value, throw error

Topic:

Optional, Optional.map, Optional.flatMap

Screenshots (if any):

OpenJDK's Optional.map and Optional.flatMap source code: image

Comic Representation: flatMap_vs_map

Clone this wiki locally