Java Language Optional FlatMap

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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())

Got any Java Language Question?