Lambda: Optional.orElseGet takes a Supplier lambda that runs only when needed

orElseGet accepts a Supplier so the fallback value is computed lazily, only when the Optional is empty, unlike orElse whose argument is always evaluated even when the Optional already holds a value.

Code
int[] fallbackCalls = {0};
Supplier<String> fallback = () -> {
    fallbackCalls[0]++;
    return "default";
};
Optional<String> present = Optional.of("configured");
Optional<String> empty = Optional.empty();
System.out.println("present: " + present.orElseGet(fallback));
System.out.println("empty: " + empty.orElseGet(fallback));
System.out.println("fallback calls: " + fallbackCalls[0]);
Output
present: configured
empty: default
fallback calls: 1
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms