Map

suggest change

Use the map() method of Optional to work with values that might be null without doing explicit null checks:

(Note that the map() and filter() operations are evaluated immediately, unlike their Stream counterparts which are only evaluated upon a terminal operation.)

Syntax:

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

Code examples:

String value = null;

return Optional.ofNullable(value).map(String::toUpperCase).orElse("NONE");
// returns "NONE"
String value = "something";

return Optional.ofNullable(value).map(String::toUpperCase).orElse("NONE");
// returns "SOMETHING"

Because Optional.map() returns an empty optional when its mapping function returns null, you can chain several map() operations as a form of null-safe dereferencing. This is also known as Null-safe chaining.

Consider the following example:

String value = foo.getBar().getBaz().toString();

Any of getBar, getBaz, and toString can potentially throw a NullPointerException.

Here is an alternative way to get the value from toString() using Optional:

String value = Optional.ofNullable(foo)
                       .map(Foo::getBar)
                       .map(Bar::getBaz)
                       .map(Baz::toString)
                       .orElse("");

This will return an empty string if any of the mapping functions returned null.

Below is an another example, but slightly different. It will print the value only if none of the mapping functions returned null.

Optional.ofNullable(foo)
        .map(Foo::getBar)
        .map(Bar::getBaz)
        .map(Baz::toString)
        .ifPresent(System.out::println);

Feedback about page:

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


Optional:
* Map
* Filter

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