Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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.empty

Notes

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

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.