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

Lazy Evaluation in or: Supplier-Based Alternatives

Explore how or() takes a Supplier<Optional<T>> for lazy evaluation of fallback sources.

Lazy Evaluation in or: Supplier-Based Alternatives

What you'll learn: How or() uses a Supplier to lazily compute fallback Optional values only when needed.

Why Lazy Evaluation Matters

Remember how orElseGet() uses a Supplier to avoid computing expensive default values unless necessary? The or() method applies the same principle, but instead of producing a raw value, it produces an alternative Optional.

The key insight: the Supplier<Optional<T>> passed to or() is only invoked if the original Optional is empty. This lazy evaluation prevents unnecessary computation and allows you to chain potentially expensive fallback sources efficiently.

How It Works

When you call optional.or(supplier), Java checks the original Optional first:

  • If the original contains a value, the supplier never runs—the original is returned immediately
  • If the original is empty, only then does Java invoke the supplier to get the alternative Optional

This matters when your fallback involves database queries, API calls, file I/O, or complex calculations. You don't want to perform those operations if the first Optional already has what you need.

The Pattern

Think of it like a cascading search: "Check my cache. If empty, then check the database. If that's empty, then check the remote service." Each subsequent check only happens if all previous ones failed, because each is wrapped in a Supplier that only executes when needed.

Without lazy evaluation, you'd compute all alternatives eagerly—wasting resources on operations you might never use.

Key Takeaway: The or() method's Supplier<Optional<T>> parameter enables lazy evaluation, ensuring fallback Optional sources are only computed when the original Optional is empty, making it efficient for expensive operations.