Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

The Optional class

Reference for java.util.Optional: creating, transforming and unwrapping optional values, the primitive variants, and when not to use Optional.

java.util.Optional<T> is a small immutable container that either holds one non-null value or is empty. It exists so that a method can say in its return type "there may be no result", instead of returning null and relying on callers to remember the check. It was added in Java 8 and gained ifPresentOrElse, or and stream in Java 9, isEmpty in Java 11 and the no-argument orElseThrow() in Java 10.

Optional has a functional style API: you transform the value with map and flatMap, filter it, and finally unwrap it with a default or an exception. Primitive versions exist: OptionalInt, OptionalLong and OptionalDouble.

Java
public final class Optional<T>

Try it

Java Creating, transforming and unwrapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java flatMap, streams and primitive optionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Method Description
static <T> Optional<T> of(T value) Wraps a non-null value; throws NullPointerException for null.
static <T> Optional<T> ofNullable(T value) Wraps the value, or returns empty for null.
static <T> Optional<T> empty() The empty optional.
boolean isPresent() / isEmpty() Presence checks (isEmpty since Java 11).
T get() The value, or NoSuchElementException. Prefer the alternatives below.
T orElseThrow() Same as get() with a clearer name (Java 10).
T orElse(T other) The value or other; other is always evaluated.
T orElseGet(Supplier<? extends T> s) The value or the supplier's result (lazy).
<X extends Throwable> T orElseThrow(Supplier<? extends X> s) throws X The value, or throws the supplied exception.
<U> Optional<U> map(Function<? super T, ? extends U> f) Transforms the value; a null result gives empty.
<U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> f) Like map for functions that already return an Optional.
Optional<T> filter(Predicate<? super T> p) Keeps the value only if the predicate matches.
Optional<T> or(Supplier<? extends Optional<? extends T>> s) Alternative optional if empty (Java 9).
void ifPresent(Consumer<? super T>) / ifPresentOrElse(Consumer, Runnable) Side effects (the latter since Java 9).
Stream<T> stream() A stream of zero or one element (Java 9).

Usage notes

  • Use it for return types, not for fields, method parameters, collection elements or serialization. Optional is not Serializable, adds an object per value, and an Optional parameter can itself be null, which defeats the point.
  • Never return null from a method that returns Optional.
  • orElse evaluates its argument eagerly. Use orElseGet when the default is expensive or has side effects.
  • Avoid isPresent() followed by get(). map/orElse, ifPresentOrElse and orElseThrow express the same logic without the unchecked get().
  • Do not wrap collections. Return an empty list rather than Optional<List<T>>.
  • Equality: two optionals are equal if both are empty or their values are equal. toString() gives Optional[value] or Optional.empty.
  • Value-based class: do not synchronize on an Optional or rely on its identity (==).
  • Primitive variants (OptionalInt, OptionalLong, OptionalDouble) avoid boxing but have no map or filter; use getAsInt(), orElse, ifPresent. They are returned by stream terminal operations such as max() and average().