Java SE API
Optional.orElseGet()
Run the supplier only for absence; its result may be null. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
T orElseGet(Supplier<? extends T> supplier)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| supplier | Supplier<? extends T> | Fallback computation |
Return Value
T
Run the supplier only for absence; its result may be null.
Working Example
Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { int[] calls = {0}; java.util.function.Supplier<String> fallback = () -> { calls[0]++; return "default"; }; var present = Optional.of("stored"); System.out.println(present.orElse(fallback.get()) + ":" + calls[0]); System.out.println(present.orElseGet(fallback) + ":" + calls[0]); System.out.println(Optional.<String>empty().orElseGet(fallback) + ":" + calls[0]); }}