Java Language Optional FlatMap


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 an Optional, and if invoked, flatMap does not wrap it with an additional Optional.

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, you will get a nested Optional; i.e. Optional<Optional<Bar>>.

Optional<Optional<Bar>> nestedOptionalBar =
    Optional.of(new Foo())

However, if you use Optional.flatMap, you will get a simple Optional; i.e. Optional<Bar>.

Optional<Bar> optionalBar =
    Optional.of(new Foo())