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.

The three ways of unwrapping, and what each one costs
MethodWhen absentThe argument is evaluated
orElse(value)Returns the value you suppliedAlways, even when present
orElseGet(supplier)Calls the supplier and returns what it givesOnly when absent
orElseThrow(supplier)Throws the exception the supplier buildsOnly when absent
java
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.