Course contentsShow
← Java
Lesson 1671 of 2,87035. Functional InterfacesFree lesson

Suppliers in Optional: orElseGet

How Optional.orElseGet takes a Supplier to lazily compute a default value only if needed.

Suppliers in Optional: orElseGet

You'll learn: How Optional.orElseGet uses a Supplier to compute a default value only when the Optional is empty, avoiding unnecessary work.

The Problem with Eager Defaults

You've seen Optional.orElse(defaultValue) before. It always evaluates the default value, even if the Optional contains something. If creating that default is expensive (like a database query or complex calculation), you're wasting resources.

How orElseGet Works

Optional.orElseGet(Supplier<? extends T> supplier) takes a Supplier that produces a default value. The crucial difference: the Supplier is only invoked if the Optional is empty.

Optional<String> optName = Optional.empty();

// The Supplier lambda runs ONLY if optName is empty
String name = optName.orElseGet(() -> "Default User");

Why Lazy Evaluation Matters

Think of a Supplier as a recipe, not a cake. With orElse, you bake the cake upfront (whether you need it or not). With orElseGet, you only follow the recipe if the Optional is empty.

Optional<String> config = getConfigValue("theme");

// BAD: queryDatabase() runs even if config has a value
String theme = config.orElse(queryDatabase("default_theme"));

// GOOD: queryDatabase() only runs when needed
String theme = config.orElseGet(() -> queryDatabase("default_theme"));

Method References Shine Here

When your default comes from a simple method call, method references work beautifully:

Optional<List<String>> optList = Optional.empty();
List<String> list = optList.orElseGet(ArrayList::new);

Key Takeaway:
Use orElseGet with a Supplier when computing the default value is expensive—it ensures lazy evaluation, only doing the work when the Optional is actually empty.