Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
valueTA 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 0

Notes

It bridges old code that returns null and chains of map()/orElse(). For simple cases like a map, getOrDefault() is shorter.

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.