Choosing Between orElse and orElseGet
What you'll learn: How to decide whether to use orElse() for simple defaults or orElseGet() for expensive operations that should only run when needed.
The Core Decision
Both orElse() and orElseGet() provide fallback values when an Optional is empty, but they differ in when they compute that fallback:
orElse(value)always evaluates its argument immediately, whether the Optional has a value or notorElseGet(supplier)only calls the supplier function if the Optional is empty
This difference matters for performance and correctness.
When to Use orElse
Use orElse() when your default value is:
- A constant or literal:
optional.orElse("Unknown") - A simple variable already in scope:
optional.orElse(defaultName) - Cheap to compute and has no side effects
String name = optionalName.orElse("Guest");
int count = optionalCount.orElse(0);
When to Use orElseGet
Use orElseGet() when the default involves:
- Method calls:
optional.orElseGet(() -> fetchFromDatabase()) - Object creation:
optional.orElseGet(() -> new ArrayList<>()) - Expensive computation:
optional.orElseGet(() -> calculateDefault()) - Operations with side effects: logging, I/O, or state changes
User user = optionalUser.orElseGet(() -> createDefaultUser());
Config config = optionalConfig.orElseGet(() -> loadFromFile());
The Analogy
Think of orElse() like preparing a spare tire before checking if you need it—you do the work regardless. orElseGet() is like having a phone number for roadside assistance—you only call if necessary.
Key Takeaway: Use orElse() for constants and cheap values; use orElseGet() for method calls, object creation, or any operation you want to defer until absolutely needed.