or vs Java 8 Alternatives: Avoiding Nested orElseGet
You'll learn how or() simplifies fallback chains that would require awkward nested orElseGet calls in Java 8.
The Java 8 Problem: Nested orElseGet
Before Java 9's or() method, chaining multiple Optional sources required verbose workarounds. The most common approach involved nesting Optional.ofNullable() inside orElseGet, which quickly became unreadable:
// Java 8: Trying to chain Optional sources
Optional<String> result = getPrimary()
.map(Optional::of)
.orElseGet(() -> getSecondary()
.map(Optional::of)
.orElseGet(() -> getTertiary()));
This pattern is confusing because you're mixing map transformations with orElseGet fallbacks just to keep everything as Optional.
The Cleaner Alternative: or()
The or() method was designed specifically for this scenario—providing an alternative Optional when the first is empty:
// Java 9+: Clean fallback chain
Optional<String> result = getPrimary()
.or(() -> getSecondary())
.or(() -> getTertiary());
Why or() Wins
Think of it like a safety net ladder: With nested orElseGet, you're climbing down awkwardly, wrapping and unwrapping values at each level. With or(), you're smoothly sliding from one potential source to the next, staying in Optional-land the entire time.
The or() method keeps your intent clear: "Try this source, if empty try the next, if empty try the next." No manual wrapping, no mental overhead.
Key Takeaway: Use or() for chaining Optional sources instead of nesting orElseGet with Optional.ofNullable—it's more readable, expresses intent clearly, and was designed specifically for fallback chains.