Optional.or() fallback
Chain Optional fallbacks without nested checks.
Porównanie kodu
✕ 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);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Chainable
Stack fallbacks in a readable pipeline.
Lazy evaluation
Fallback suppliers only execute if needed.
Declarative
Reads as 'try primary, or secondary, or defaults'.
Stare podejście
Nested Fallback
Nowoczesne podejście
.or() chain
Od JDK
9
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Optional.or() fallback
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
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.
Powiązana dokumentacja