Card 03/ 08
All 8 cards
ComparisonDifficulty: Intermediate1 min
orElse, orElseGet and orElseThrow
Three methods for getting a value out of an Optional, and the choice between them is about what should happen when there is nothing in it.
| Method | When absent | The argument is evaluated |
|---|---|---|
orElse(value) | Returns the value you supplied | Always, even when present |
orElseGet(supplier) | Calls the supplier and returns what it gives | Only when absent |
orElseThrow(supplier) | Throws the exception the supplier builds | Only when absent |
String a = found.orElse("unknown");
Customer b = found.orElseGet(() -> loadFromBackupStore(ref));
Customer c = found.orElseThrow(() -> new NoSuchCustomer(ref));The decision rule. Use orElse for a cheap constant that is already in hand. Use orElseGet whenever producing the fallback costs anything at all — a database call, an allocation, a computation. Use orElseThrow when absence is a failure rather than a case to handle.
Prefer map, filter and ifPresent to any of these three where they fit. Unwrapping is how you leave Optional, and staying inside it is usually shorter.