Course contentsShow
← Java
Lesson 1812 of 2,87037. Optional for Null SafetyFree lesson

Chaining Multiple or Calls for Fallback Logic

Chain multiple or() invocations to try several sources in sequence until a non-empty Optional is found.

Chaining Multiple or Calls for Fallback Logic

What you'll learn: How to create a cascading series of fallback sources by chaining multiple or() calls together.

The Fallback Chain Pattern

Since or() returns an Optional, you can chain multiple or() calls to try several sources in sequence until you find a non-empty result. This creates an elegant fallback chain without nested conditionals or temporary variables.

Think of it like checking your pockets for your keys: first your jacket, then your pants, then your bag, then your car—stopping as soon as you find them.

How Chaining Works

Each or() in the chain is only evaluated if all previous Optionals were empty. Once any source returns a non-empty Optional, the chain short-circuits and stops evaluating further suppliers:

Optional<String> result = tryPrimarySource()
    .or(() -> trySecondarySource())
    .or(() -> tryTertiarySource())
    .or(() -> Optional.of("ultimate fallback"));

The suppliers are lazy—they execute only when needed. If tryPrimarySource() returns a non-empty Optional, the other methods never run.

Practical Example

Optional<User> user = findInCache(userId)
    .or(() -> findInDatabase(userId))
    .or(() -> findInLegacySystem(userId))
    .or(() -> Optional.empty());

This pattern is especially powerful for resource lookup strategies: try the fastest source first (cache), then slower but more comprehensive sources (database, external APIs), gracefully degrading through your options.

Combining With Terminal Operations

After your or() chain, use terminal operations to extract the value:

String result = source1()
    .or(() -> source2())
    .or(() -> source3())
    .orElse("default");

Key Takeaway: Chain multiple or() calls to create readable, lazy-evaluated fallback logic that tries sources in sequence until finding a value, avoiding nested if-else pyramids and executing only necessary suppliers.