Lazily provide a default value using a Supplier
suggest changeThe 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents