GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Optional.or() fallback | java.evolved

Home / Streams / Optional.or() fallback
Streams Intermediate

Optional.or() fallback

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Chain Optional fallbacks without nested checks.

Optional
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);
Share 𝕏
See a problem with this code? Let us know.
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
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
Optional.or() ↗
Proof
View proof source ↗
Related patterns
Streams Intermediate

Stream.iterate() with predicate

Java 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
Hover to see modern ➜
JDK 9+ →
Streams Advanced

Stream gatherers

Java 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();
Hover to see modern ➜
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);
Hover to see modern ➜
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.