OrElse Eager Versus OrElseGet Lazy
orElse evaluates its argument even on a cache hit, while orElseGet invokes the supplier only when the Optional is empty.
Code
import java.util.Optional;
public class CacheLookup {
static String expensiveFallback() {
System.out.println(" [fallback computed]");
return "computed";
}
public static void main(String[] args) {
Optional<String> cached = Optional.of("cached-value");
// orElse 的参数是普通实参:eager 求值,命中缓存也白算一次 fallback
System.out.println("orElse, hit:");
String a = cached.orElse(expensiveFallback());
// orElseGet 接 Supplier:lazy 语义,命中时完全不执行
System.out.println("orElseGet, hit:");
String b = cached.orElseGet(CacheLookup::expensiveFallback);
System.out.println("a = " + a + ", b = " + b);
// 未命中时两者行为一致,都落到 fallback
Optional<String> missing = Optional.empty();
System.out.println("orElse, miss: " + missing.orElse(expensiveFallback()));
System.out.println("orElseGet, miss: " + missing.orElseGet(CacheLookup::expensiveFallback));
}
}Inside the snippet
OrElse Eager Versus OrElseGet Lazy comes down to the class CacheLookup and the functions expensiveFallback and main.
Optional makes the possibly-missing value explicit at the type level.
Putting it to use
The main signature reads static String expensiveFallback()
The run emits 6 labeled sections — [fallback computed], orElse, hit:, orElseGet, hit:, a =, orElse, miss:, orElseGet, miss: — one per step.
The entry point wires expensiveFallback together — run it once and the whole demo flows.
Core lines
Optional<String> cached = Optional.of("cached-value");
Optional<String> missing = Optional.empty();
return "computed";
Interactive Tools for This Topic
HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- What does OrElse Eager Versus OrElseGet Lazy print when run?
- No setup needed: run the file and look for labeled lines like `[fallback computed]`, `orElse, hit:`, `orElseGet, hit:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.