Java Optional ofNullable() Method
Example
Create an Optional from a value, and from null:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.ofNullable("Liam");
Optional<String> noName = Optional.ofNullable(null);
System.out.println(name.orElse("Guest"));
System.out.println(noName.orElse("Guest"));
}
}
Definition and Usage
The ofNullable() method returns an Optional that holds the value. If the value is null, it returns an empty Optional.
Use it when the value can be null, for example a value from HashMap get(), which returns null when the key does not exist.
Syntax
public static <T> Optional<T> ofNullable(T value)
T refers to the data type of the value.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to put in the Optional. It can be null. |
Technical Details
| Returns: | An Optional that holds the value, or an empty Optional if the value is null. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods