Short answer:
- orElse () will always call this function, whether you want it or not, regardless of the value of
Optional.isPresent() - orElseGet () will call this function only when
Optional.isPresent() == false
In real code, you can consider the second approach when the required resource is expensive .
// Always get heavy resource getResource(resourceId).orElse(getHeavyResource()); // Get heavy resource when required. getResource(resourceId).orElseGet(() -> getHeavyResource())
For more information, consider the following example with this function:
public Optional<String> findMyPhone(int phoneId)
The difference is as below:
X : buyNewExpensivePhone() called +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ββββββββββββββ+ | Optional.isPresent() | true | false | +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ββββββββββββββ+ | findMyPhone(int phoneId).orElse(buyNewExpensivePhone()) | X | X | +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ββββββββββββββ+ | findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) | | X | +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ββββββββββββββ+
If optional.isPresent() == false , there is no difference between the two methods. However, when orElse() optional.isPresent() == true , orElse() always calls the next function, whether you want it or not.
And finally, the test case used, as shown below:
Result:
The code:
public class TestOptional { public Optional<String> findMyPhone(int phoneId) { return phoneId == 10 ? Optional.of("MyCheapPhone") : Optional.empty(); } public String buyNewExpensivePhone() { System.out.println("\tGoing to a very far store to buy a new expensive phone"); return "NewExpensivePhone"; } public static void main(String[] args) { TestOptional test = new TestOptional(); String phone; System.out.println("------------- Scenario 1 - orElse() --------------------"); System.out.println(" 1.1. Optional.isPresent() == true"); phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone()); System.out.println("\tUsed phone: " + phone + "\n"); System.out.println(" 1.2. Optional.isPresent() == false"); phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone()); System.out.println("\tUsed phone: " + phone + "\n"); System.out.println("------------- Scenario 2 - orElseGet() --------------------"); System.out.println(" 2.1. Optional.isPresent() == true");
nxhoaf Dec 23 '17 at 9:41 on 2017-12-23 09:41
source share