Java Optional
In this mini article or even a fast reminder for self, I will explain the following:
- The difference between map and flatmap for Java Optional.
- When to use map and when to use flatmap
At the beginning of becoming a fanboy for java.util.Optional, I was a little bit confused about when to use map, flatmap? What each one returns back? Does it invokes orElse methods or not?
Difference between map() and flatmap()
After some investigation, I could get to a difference:
map():
Process: takes the object, maps it using the specified criteria.
Returns: the plain result from the processing wrapped in an Optional object (e.g. Optional<String>).
The elseOr function, if exists, checks for the value inside this optional and decides either to return the original Optional or an empty one (Optional.empty()).
flatmap():
Works exactly the same as map(), but it the whole difference is in the return value!
It returns the plain result as it after the mapping has been done, either using a Lambda expression or an explicit function call, WITHOUT wrapping it in an Optional object.
When to use each one
That being mentioned:
Get Ahmed ElGamal’s stories in your inbox
Join Medium for free to get updates from this writer.
map(): shall only be used when the function called returns a non-Optional value (e.g. returns a String).
flatmap(): shall be used when the mapper function used returns Optional, since the flatmap does not wrap the value in extra Optional layer, the returned value will be wrapped in only one Optional layer (the one coming form the Mapper method aka coming from the processing).
Adding null Safety
- Using .ofNullable(), wrap the main object in an Optional.
- Using .map(), make sure all inner nested attributes are present.
- Inside ifPresent(), call the mapper function, in case no previous null was found.
Example
Null non-safe:
public void printPersonVisaNumber(final PersonData personData) {
System.out.println(personData.getCardData().getVisaNumber());
}Null safe:
public void printPersonVisaNumber(final PersonData personData) {
Optional.ofNullable(personData)
.map(PersonData::getCardData)
.map(CardData::getVisaNumber)
.ifPresent(System.out::println);
}Resources:


