flatMap is similar to map. The difference is described by the javadoc as follows:
This method is similar to
map(Function), but the provided mapper is one whose result is already anOptional, and if invoked,flatMapdoes not wrap it with an additionalOptional.
In other words, when you chain a method call that returns an Optional, using Optional.flatMap avoids creating nested Optionals.
For example, given the following classes:
public class Foo {
Optional<Bar> getBar(){
return Optional.of(new Bar());
}
}
public class Bar {
}
If you use Optional.map, you will get a nested Optional; i.e. Optional<Optional<Bar>>.
Optional<Optional<Bar>> nestedOptionalBar =
Optional.of(new Foo())
.map(Foo::getBar);
However, if you use Optional.flatMap, you will get a simple Optional; i.e. Optional<Bar>.
Optional<Bar> optionalBar =
Optional.of(new Foo())
.flatMap(Foo::getBar);