What\'s the difference between these two methods: Optional.flatMap() and Optional.map()?
An example would be appreciated.
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?
Your result is now an Optional!
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.
It's the composition of two functional idioms: map and flatten.