java.util · java.base · since Java 1.8
Optional
public final class Optional<T>A maybe-value return type: forces callers to confront absence. Consume with orElse/map/ifPresent; never bare get(); not for fields or parameters (EJ 55).
Key methods
static <T> Optional<T> of(T) / ofNullable(T) / empty() | Creation (of(null) throws). |
boolean isPresent() / boolean isEmpty() | Presence checks — prefer ifPresent/map/orElse over branching on these when possible. |
T orElse(T other) / T orElseGet(Supplier<T>) | Defaults — orElse's argument is ALWAYS evaluated. |
T orElseThrow(Supplier<X>) | Fail with a meaningful exception. |
Optional<T> filter(Predicate<? super T>) | Keep the value only if it matches the predicate; otherwise becomes empty. |
Optional<U> map(Function) / flatMap(Function) | Transform if present. |
Optional<T> or(Supplier<? extends Optional<? extends T>>) | Lazy fallback Optional — the supplier runs only when this Optional is empty. |
void ifPresent(Consumer) / ifPresentOrElse(…) | Conditional actions. |
Stream<T> stream() | 0-or-1 element stream — flatMap-friendly. |