Map,Return default value and Throw an exception


Optional

Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence of the contained value are provided, such as orElse(), which returns a default value if value not present, and ifPresent() which executes a block of code if the value is present.


Map

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)

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

Return default value if Optional is empty

Don't just use Optional.get() since that may throw NoSuchElementException. The Optional.orElse(T) and Optional.orElseGet(Supplier<? extends T>) methods provide a way to supply a default value in case the Optional is empty.

String value = "something";
 
return Optional.ofNullable(value).orElse("defaultValue");
// returns "something"
 
return Optional.ofNullable(value).orElseGet(() -> getDefaultValue());
// returns "something" (never calls the getDefaultValue() method)
 
String value = null;
 
return Optional.ofNullable(value).orElse("defaultValue");
// returns "defaultValue"
 
return Optional.ofNullable(value).orElseGet(() -> getDefaultValue());
// calls getDefaultValue() and returns its results

The crucial difference between the orElse and orElseGet is that the latter is only evaluated when the Optional is empty while the argument supplied to the former one is evaluated even if the Optional is not empty. The orElse should therefore only be used for constants and never for supplying value based on any sort of computation.


Throw an exception, if there is no value

Use the orElseThrow() method of Optional to get the contained value or throw an exception, if it hasn't been set. This is similar to calling get(), except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown.

In the first example, the method simply returns the contained value:

Optional optional = Optional.of("something");
 
return optional.orElseThrow(IllegalArgumentException::new);
// returns "something" string
 
In the second example, the method throws an exception because a value hasn't been set:
 
Optional optional = Optional.empty();
 
return optional.orElseThrow(IllegalArgumentException::new);
// throws IllegalArgumentException
 
You can also use the lambda syntax if throwing an exception with message is needed:
 
optional.orElseThrow(() -> new IllegalArgumentException("Illegal"));

Lazily provide a default value using a Supplier

The normal orElse method takes an Object, so you might wonder why there is an option to provide a Supplier here (the orElseGet method).

Consider:

String value = "something";
return Optional.ofNullable(value)
       .orElse(getValueThatIsHardToCalculate()); // returns "something"

It would still call getValueThatIsHardToCalculate() even though it's result is not used as the optional is not empty.

To avoid this penalty you supply a supplier:

String value = "something";
return Optional.ofNullable(value)
       .orElseGet(() -> getValueThatIsHardToCalculate()); // returns "something"

This way getValueThatIsHardToCalculate() will only be called if the Optional is empty.

Basic Programs