orElseorElseGetorElseThrow
orElseorElseGetorElseThrow is a shorthand reference to the trio of methods in Java's Optional type that handle empty values: orElse, orElseGet, and orElseThrow. They provide different strategies for obtaining a value when the Optional is empty and are commonly used to express fallback behavior in a fluent style.
orElse(T other) returns the contained value if present; otherwise it returns the provided other value. The other
orElseGet(Supplier<? extends T> supplier) returns the contained value if present; otherwise it calls supplier.get() to obtain
orElseThrow() returns the contained value if present; otherwise it throws NoSuchElementException. There is also orElseThrow(Supplier<? extends
Usage considerations include choosing between eager and lazy fallbacks (orElse vs orElseGet) and deciding whether a
Optional<String> opt = Optional.ofNullable(getName());
String a = opt.orElse("default");
String b = opt.orElseGet(() -> computeDefaultName());
String c = opt.orElseThrow(() -> new IllegalStateException("Name missing"));