Java 8 - Difference between Optional.flatMap and Optional.map
Solution 1:
Use map
if the function returns the object you need or flatMap
if the function returns an Optional
. For example:
public static void main(String[] args) {
Optional<String> s = Optional.of("input");
System.out.println(s.map(Test::getOutput));
System.out.println(s.flatMap(Test::getOutputOpt));
}
static String getOutput(String input) {
return input == null ? null : "output for " + input;
}
static Optional<String> getOutputOpt(String input) {
return input == null ? Optional.empty() : Optional.of("output for " + input);
}
Both print statements print the same thing.
Solution 2:
They both take a function from the type of the optional to something.
map()
applies the function "as is" on the optional you have:
if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));
What happens if your function is a function from T -> Optional<U>
?
Your result is now an Optional<Optional<U>>
!
That's what flatMap()
is about: if your function already returns an Optional
, flatMap()
is a bit smarter and doesn't double wrap it, returning Optional<U>
.
It's the composition of two functional idioms: map
and flatten
.