orElse
The Optional methods that turn an Optional back into a plain value: orElse with a fallback, orElseGet with a fallback computed only if needed, and orElseThrow with an exception.
In more detail
orElse evaluates its argument even when a value is present, which is fine for a cheap constant. orElseGet takes a supplier that runs only when the Optional is empty, which suits expensive fallbacks. orElseThrow with no arguments throws NoSuchElementException, which the course service lets advice translate into a not found response.
Examples
value.orElse("MISSING")orders.findById(id).map(this::view).orElseThrow()Related terms
- Optional — A container that holds either one value or nothing, used as a return type to make "no result" visible to the caller.
- Supplier — A functional interface whose get method takes no arguments and returns a value, used to produce something on demand.
Taught in
- Handling Nulls With Optional — Modern Java: Virtual Threads & High-Throughput Services
- Tying It All Together — Modern Java: Virtual Threads & High-Throughput Services