An immutable object that may contain a non-null reference to another object. Each instance of
this type either contains a non-null reference, or contains nothing (in which case we say that
the reference is "absent"); it is never said to "contain
null".
A non-null
Optional reference can be used as a replacement for a nullable
Treference. It allows you to represent "a
T that must be present" and a
"a
T that might be absent" as two distinct types in your program, which can aid clarity.
Some uses of this class include
- As a method return type, as an alternative to returning
null to indicate that no
value was available
- To distinguish between "unknown" (for example, not present in a map) and "known to have no
value" (present in the map, with value
Optional.absent())
- To wrap nullable references for storage in a collection that does not support
null(though there are
several other
approaches to this that should be considered first)
A common alternative to using this class is to find or create a suitable
null object for the type in
question.
This class is not intended as a direct analogue of any existing "option" or "maybe" construct
from other programming environments, though it may bear some similarities.
Comparison to
java.util.Optional (JDK 8 and higher): A new
Optionalclass was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
share a common supertype). All known differences are listed either here or with the
relevant methods below.
- This class is serializable;
java.util.Optional is not.
-
java.util.Optional has the additional methods
ifPresent,
filter,
flatMap, and
orElseThrow.
-
java.util offers the primitive-specialized versions
OptionalInt,
OptionalLong and
OptionalDouble, the use of which is recommended; Guava does not
have these.
There are no plans to deprecate this class in the foreseeable future. However, we do
gently recommend that you prefer the new, standard Java class whenever possible.
See the Guava User Guide article on
using
Optional.