Optional.ofNullable()
Wraps a value that may be `null` into an `Optional`.
Available since: Java 8
Syntax
static <T> Optional<T> ofNullable(T value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | T | A value that may be `null`. |
Return value
Optional<T>An `Optional` with the value, or an empty one if `null` was passed.
Examples
Working safely with the result of Map.get():
void main() {
Map<String, Integer> stock = Map.of("tea", 5);
int tea = Optional.ofNullable(stock.get("tea")).orElse(0);
int milk = Optional.ofNullable(stock.get("milk")).orElse(0);
IO.println(tea + " " + milk);
}Output:
5 0Notes
It bridges old code that returns null and chains of map()/orElse(). For simple cases like a map, getOrDefault() is shorter.
See also
- Optional.of() — Creates an `Optional` holding a non-null value.
- Optional.empty() — Returns an empty `Optional` — no value.
- Map.get() — Returns the value for a key, or `null`.
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.