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

Taught in

References