Home >Java >javaTutorial >When should you use Optional.orElseGet() instead of Optional.orElse()?
Difference between Optional.orElse() and Optional.orElseGet()
The Optional class provides methods like orElse() and orElseGet() to retrieve the value from an Optional if it is present, or provide a default value if it is empty. However, there is a subtle difference in their behavior:
When to Use orElseGet()
The key difference is that orElseGet() delays the execution of the default value retrieval function until it is needed, while orElse() always executes the function. This can be important in situations where obtaining the default value is an expensive or time-consuming operation that you only want to perform if necessary.
Example:
Consider a scenario where you need to find a resource (represented by an Optional) and retrieve its value, or else provide a default value. If obtaining the default value requires a costly database query, you would want to use orElseGet() to avoid the query when the resource is present.
<code class="java">Optional<Resource> resource = findResource(); Resource result = orElseGet(() -> getExpensiveDefaultValue());</code>
Additional Notes:
Conclusion:
orElseGet() provides a way to defer the execution of a default value retrieval function until it is necessary, allowing performance optimizations in cases where obtaining the default value is expensive or undesirable when the Optional is non-empty.
The above is the detailed content of When should you use Optional.orElseGet() instead of Optional.orElse()?. For more information, please follow other related articles on the PHP Chinese website!