Stats

Contributors: 9 Wednesday, February 1, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Map

Example

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