Java Reference ยท Streams and Functional
Java Optional.of() and ofNullable()
Reference for creating Java Optional values: of(), ofNullable(), empty(), the primitive variants, and the NullPointerException that of(null) throws.
An Optional<T> is a small container that either holds one non-null value or is empty. It exists to make "there may be no result" visible in a method's return type, instead of returning null and hoping the caller checks.
You create one with a static factory method. Optional.of(value) is for a value you know is not null, Optional.ofNullable(value) converts a possibly-null reference, and Optional.empty() gives the empty instance. There are no public constructors.
Optional<String> a = Optional.of("java"); Optional<String> b = Optional.ofNullable(maybeNull); Optional<String> c = Optional.empty();
Try it
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.
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
public static <T> Optional<T> of(T value) public static <T> Optional<T> ofNullable(T value) public static <T> Optional<T> empty()
| Method | Description |
|---|---|
of(T value) |
Wraps value. Throws NullPointerException if it is null. |
ofNullable(T value) |
Wraps value, or returns the empty Optional if it is null. |
empty() |
Returns the empty Optional. |
Returns: an Optional<T>. OptionalInt, OptionalLong and OptionalDouble have of(x) and empty() but no ofNullable(), since primitives cannot be null.
Usage notes
- Pick by certainty.
of()documents "this cannot be null" and fails fast on a bug.ofNullable()is for values that really can be missing, such asmap.get(key)or a field loaded from a database. - Return type only. Optional was designed for method return values. Avoid it for fields, constructor or method parameters, and collection elements: it adds an object, is not
Serializable, and callers can still passnullfor the Optional itself. - Never return
nullfrom a method that returns Optional. ReturnOptional.empty(). - Never call
get()blindly. On an empty Optional it throwsNoSuchElementException. PreferorElse,orElseGet,orElseThroworifPresent; seeoptional-get-orelse. - Identity. Optional is a value-based class: do not synchronize on it, and do not compare with
==(althoughempty()happens to be a singleton). Useequals(). - Streams.
Stream.findFirst(),max(),min(),reduce(op)and similar methods return Optionals;Optional.stream()(Java 9) turns one into a stream of zero or one element. Optional.toString()printsOptional[value]orOptional.empty.