Return default value if Optional is empty

suggest change

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.

Feedback about page:

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



Table Of Contents