GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Optional.or() fallback | java.evolved
Streams
Intermediate
Optional.or() fallbackChain Optional fallbacks without nested checks. Code Comparison
✕ 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);
See a problem with this code? Let us know.
Why the modern way wins
🔗
ChainableStack fallbacks in a readable pipeline. ⚡
Lazy evaluationFallback suppliers only execute if needed. 📖
DeclarativeReads as 'try primary, or secondary, or defaults'. Old Approach
Nested Fallback
Modern Approach
.or() chain
Since JDK
9
Difficulty
Intermediate
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
Related patterns
Streams
Intermediate
Stream.iterate() with predicateJava 8
Stream.iterate(1, n -> n * 2)
.limit(10)
.forEach(System.out::println);
// can't stop at a condition
Java 9+
Stream.iterate(
1,
n -> n < 1000,
n -> n * 2
).forEach(IO::println);
// stops when n >= 1000
JDK 9+
→
Streams
Advanced
Stream gatherersJava 8
// Sliding window: manual implementation
List<List<T>> windows = new ArrayList<>();
for (int i = 0; i <= list.size()-3; i++) {
windows.add(
list.subList(i, i + 3));
}
Java 24+
var windows = stream
.gather(
Gatherers.windowSliding(3)
)
.toList();
JDK 24+
→
Streams
Beginner
Stream.ofNullable()Java 8
Stream<String> s = val != null
? Stream.of(val)
: Stream.empty();
Java 9+
Stream<String> s =
Stream.ofNullable(val);
JDK 9+
→
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |