Lazily provide a default value using a Supplier

suggest change

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.

Feedback about page:

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



Table Of Contents