Optional
A container that either holds a value or is empty — a replacement for returning `null`.
Available since: Java 8
Syntax
public final class Optional<T>Examples
A method that may find nothing:
Optional<String> findEmail(String name) {
Map<String, String> emails = Map.of("Anna", "anna@mail.com");
return Optional.ofNullable(emails.get(name));
}
void main() {
IO.println(findEmail("Anna").orElse("no email"));
IO.println(findEmail("Oleg").orElse("no email"));
IO.println(findEmail("Oleg"));
}Output:
anna@mail.com
no email
Optional.emptyNotes
Optional makes a missing value an explicit part of the type: the caller sees that there may be no result. It is used as a return type, not for class fields or method parameters. An Optional itself must never be null.
See also
- Optional.ofNullable() — Wraps a value that may be `null` into an `Optional`.
- Optional.orElse() — Returns the value, or a fallback if there is none.
- Optional.map() — Transforms the value inside an `Optional` if there is one.
- Stream.findFirst() — Returns the first stream element as an `Optional`.
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.