Optional.or() fallback
Code Comparison
Optional<Config> cfg = primary();
if (!cfg.isPresent()) {
cfg = secondary();
}
if (!cfg.isPresent()) {
cfg = defaults();
}
Optional<Config> cfg = primary()
.or(this::secondary)
.or(this::defaults);
Why the modern way wins
๐
Chainable
Stack fallbacks in a readable pipeline.
โก
Lazy evaluation
Fallback suppliers only execute if needed.
๐
Declarative
Reads as 'try primary, or secondary, or defaults'.
Old Approach
Nested Fallback
Modern Approach
.or() chain
JDK Support
Optional.or() fallback
Available
Widely available since JDK 9 (Sept 2017)
How it works
Optional.or() returns the original Optional if it has a value, otherwise evaluates the supplier to get an alternative Optional. Suppliers are lazy โ only called when needed.
Related Documentation
Proof