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

The or Method: Providing Alternative Optionals

Learn how Optional.or() returns an alternative Optional if the current one is empty, enabling fallback chains.

The or Method: Providing Alternative Optionals

You'll learn how to use Optional.or() to provide fallback Optional chains when your primary Optional is empty.

The Problem with orElse and orElseGet

You've learned to use orElse() and orElseGet() to unwrap an Optional and provide a fallback value. But what if your fallback itself comes from another operation that might also be absent? You don't want to unwrap the Optional just to rewrap it again.

How or() Works

The or() method (introduced in Java 9) takes a Supplier<Optional<T>> and returns an alternative Optional if the current one is empty. If the current Optional has a value, or() returns it unchanged—the supplier is never called.

Signature:

Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)

The Fallback Chain Pattern

Think of or() as a chain of "Plan B" options, where each link in the chain is itself an Optional. You stay in the Optional world throughout:

Optional<String> primary = Optional.empty();
Optional<String> secondary = Optional.of("fallback");

Optional<String> result = primary.or(() -> secondary);
// result contains "fallback"

You can chain multiple or() calls:

Optional<String> result = getPrimaryConfig()
    .or(() -> getSecondaryConfig())
    .or(() -> getDefaultConfig());

Each fallback is only evaluated if all previous Optionals were empty.

or() vs orElseGet()

  • orElseGet() returns the unwrapped value (exits the Optional context)
  • or() returns another Optional (stays in the Optional context for further chaining)

Key Takeaway: Use Optional.or() to lazily provide alternative Optional sources in a fallback chain, keeping your code in the Optional pipeline until you're ready to extract or consume the final value.