Stats

Contributors: 7
Saturday, June 3, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Lazily provide a default value using a Supplier

Download java eBook

Example

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.