Optional.orElse()
Returns the value, or a fallback if there is none.
Available since: Java 8
Syntax
T orElse(T other)Parameters
| Parameter | Type | Description |
|---|---|---|
| other | T | The default value. |
Return value
TThe value from the `Optional`, or `other`.
Examples
A user name or guest:
void main() {
Optional<String> name = Optional.empty();
IO.println(name.orElse("guest"));
IO.println(Optional.of("Anna").orElse("guest"));
}Output:
guest
AnnaNotes
The argument is always evaluated, even when a value is present. If the fallback is expensive to create (a query, a big object), use orElseGet().
See also
- Optional.orElseGet() — Returns the value, or calls a function to create a fallback.
- Optional.orElseThrow() — Returns the value or throws an exception if there is none.
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
Related recipes
In the tutorial
- Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.