Streams intermediate

Optional.or() fallback

Chain Optional fallbacks without nested checks.

✕ Java 8
Optional<Config> cfg = primary();
if (!cfg.isPresent()) {
    cfg = secondary();
}
if (!cfg.isPresent()) {
    cfg = defaults();
}
✓ Java 9+
Optional<Config> cfg = primary()
    .or(this::secondary)
    .or(this::defaults);
🔗

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
Since JDK
9
Difficulty
intermediate
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.

Share 𝕏 🦋 in