Contributors: 7 Saturday, June 3, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

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


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.