Return the value if present, otherwise invoke a supplier.
The orElseGet() method returns the value if present, otherwise invokes the given Supplier and returns the result. Unlike orElse(), the supplier is only called when the Optional is empty, making it suitable for expensive default computations.
This lazy evaluation is the key difference from orElse(). Use orElseGet() when the default value requires a database query, network call, complex calculation, or any operation you want to avoid unless necessary.
The Supplier is a functional interface that takes no arguments and returns a value. Lambda expressions and method references are commonly used. For example, orElseGet(() -> computeDefault()) or orElseGet(this::getDefaultValue).
| Name | Description | Optional |
|---|---|---|
supplier |
A Supplier whose result is returned if no value is present. | No |
Optional<String> opt = Optional.of("Hello");
opt.orElseGet(() -> "default"); // "Hello"
Optional<String> empty = Optional.empty();
empty.orElseGet(() -> "computed default"); // "computed default"
// Lazy evaluation: expensive call only made if empty
empty.orElseGet(() -> fetchFromDatabase());