โ— Shell
clean mode source โ†—

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