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

orElseGet: Lazy Default Value Supplier

Master orElseGet which accepts a Supplier, evaluating the fallback only when the Optional is empty for better performance.

orElseGet: Lazy Default Value Supplier

You'll learn how to provide fallback values efficiently using orElseGet(), which only computes the default when the Optional is empty.

The Performance Problem with orElse

In the previous lesson, you learned that orElse() always evaluates its argument, even when the Optional contains a value. This becomes problematic when creating the default value is expensive—like querying a database, calling an API, or performing complex calculations.

Enter orElseGet: Lazy Evaluation

orElseGet() accepts a Supplier<T> instead of a direct value. The Supplier is only invoked if the Optional is empty. This lazy evaluation can dramatically improve performance.

Syntax:

T orElseGet(Supplier<? extends T> supplier)

How It Works

Think of orElseGet() like a vending machine with a "call for backup" button. With orElse(), the backup item is already sitting there taking up space whether you need it or not. With orElseGet(), you only call for the backup item when the machine is actually empty.

Comparison Example

// Expensive operation runs EVERY time
String result1 = optional.orElse(fetchFromDatabase());

// Expensive operation runs ONLY when optional is empty
String result2 = optional.orElseGet(() -> fetchFromDatabase());

When to Use Each

  • Use orElse() for simple, pre-computed values: orElse("default")
  • Use orElseGet() for expensive computations, method calls, or object creation: orElseGet(() -> new ArrayList<>())

Key Takeaway: orElseGet() defers the creation of default values using a Supplier, executing only when the Optional is empty—making it the performance-conscious choice for expensive fallback operations.