Determining the Difference Between Optional.orElse() and Optional.orElseGet()
In Java, the Optional class provides methods like orElse() and orElseGet() for dealing with potentially missing or null values. Understanding their nuances is crucial for effective usage.
orElse() vs. orElseGet()
When to Use orElseGet()
Example with Real-World Function
To illustrate the difference, consider the following function:
<code class="java">public Optional<String> findMyPhone(int phoneId)</code>
Scenario 1: orElse()
When optional.isPresent() == true:
When optional.isPresent() == false:
Scenario 2: orElseGet()
When optional.isPresent() == true:
When optional.isPresent() == false:
Code Example
<code class="java">public class TestOptional { public Optional<String> findMyPhone(int phoneId) { return phoneId == 10 ? Optional.of("MyCheapPhone") : Optional.empty(); } public String buyNewExpensivePhone() { System.out.println("Going to a very far store to buy a new expensive phone"); return "NewExpensivePhone"; } public static void main(String[] args) { // Scenario 1: orElse() Optional<String> phone = findMyPhone(10).orElse(buyNewExpensivePhone()); // Scenario 2: orElseGet() phone = findMyPhone(-1).orElseGet(() -> buyNewExpensivePhone()); } }</code>
The code demonstrates the different behaviors of orElse() and orElseGet() based on the presence or absence of the optional value.
The above is the detailed content of When should I use Optional.orElseGet() instead of Optional.orElse() in Java?. For more information, please follow other related articles on the PHP Chinese website!