FlatMap

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Optional:
* Map
* Filter
* FlatMap

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
28 Optional
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap