Class Optional<T>
- Type Parameters:
T
- the type of instance that can be contained.Optional
is naturally covariant on this type, so it is safe to cast anOptional<T>
toOptional<S>
for any supertypeS
ofT
.
- All Implemented Interfaces:
Serializable
null
".
A non-null Optional<T>
reference can be used as a replacement for a nullable T
reference. 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.
An instance of this class is serializable if its reference is absent or is a serializable object.
Comparison to java.util.Optional
(JDK 8 and higher): A new Optional
class 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 methodsifPresent
,filter
,flatMap
, andorElseThrow
.java.util
offers the primitive-specialized versionsOptionalInt
,OptionalLong
andOptionalDouble
, 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
.
- Since:
- 10.0
- Author:
- Kurt Alfred Kluever, Kevin Bourrillion
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Optional
<T> absent()
Returns anOptional
instance with no contained reference.asSet()
abstract boolean
Returnstrue
ifobject
is anOptional
instance, and either the contained references are equal to each other or both are absent.fromJavaUtil
(@Nullable Optional<T> javaUtilOptional) Returns the equivalentcom.google.common.base.Optional
value to the givenjava.util.Optional
, ornull
if the argument is null.static <T> Optional
<T> fromNullable
(@Nullable T nullableReference) IfnullableReference
is non-null, returns anOptional
instance containing that reference; otherwise returnsabsent()
.abstract T
get()
Returns the contained instance, which must be present.abstract int
hashCode()
Returns a hash code for this instance.abstract boolean
Returnstrue
if this holder contains a (non-null) instance.static <T> Optional
<T> of
(T reference) Returns anOptional
instance containing the given non-null reference.Returns thisOptional
if it has a value present;secondChoice
otherwise.abstract T
Returns the contained instance if it is present;supplier.get()
otherwise.abstract T
Returns the contained instance if it is present;defaultValue
otherwise.orNull()
Returns the contained instance if it is present;null
otherwise.static <T> Iterable
<T> presentInstances
(Iterable<? extends Optional<? extends T>> optionals) Returns the value of each present instance from the suppliedoptionals
, in order, skipping over occurrences ofabsent()
.Returns the equivalentjava.util.Optional
value to this optional.toJavaUtil
(@Nullable Optional<T> googleOptional) Returns the equivalentjava.util.Optional
value to the givencom.google.common.base.Optional
, ornull
if the argument is null.abstract String
toString()
Returns a string representation for this instance.abstract <V> Optional
<V>
-
Method Details
-
absent
-
of
Returns anOptional
instance containing the given non-null reference. To havenull
treated asabsent()
, usefromNullable(T)
instead.Comparison to
java.util.Optional
: no differences.- Throws:
NullPointerException
- ifreference
is null
-
fromNullable
IfnullableReference
is non-null, returns anOptional
instance containing that reference; otherwise returnsabsent()
.Comparison to
java.util.Optional
: this method is equivalent to Java 8'sOptional.ofNullable
. -
fromJavaUtil
Returns the equivalentcom.google.common.base.Optional
value to the givenjava.util.Optional
, ornull
if the argument is null.- Since:
- 21.0 (but only since 33.4.0 in the Android flavor)
-
toJavaUtil
Returns the equivalentjava.util.Optional
value to the givencom.google.common.base.Optional
, ornull
if the argument is null.If
googleOptional
is known to be non-null, usegoogleOptional.toJavaUtil()
instead.Unfortunately, the method reference
Optional::toJavaUtil
will not work, because it could refer to either the static or instance version of this method. Write out the lambda expressiono -> Optional.toJavaUtil(o)
instead.- Since:
- 21.0 (but only since 33.4.0 in the Android flavor)
-
toJavaUtil
Returns the equivalentjava.util.Optional
value to this optional.Unfortunately, the method reference
Optional::toJavaUtil
will not work, because it could refer to either the static or instance version of this method. Write out the lambda expressiono -> o.toJavaUtil()
instead.- Since:
- 21.0 (but only since 33.4.0 in the Android flavor)
-
isPresent
Returnstrue
if this holder contains a (non-null) instance.Comparison to
java.util.Optional
: no differences. -
get
Returns the contained instance, which must be present. If the instance might be absent, useor(Object)
ororNull()
instead.Comparison to
java.util.Optional
: when the value is absent, this method throwsIllegalStateException
, whereas thejava.util
counterpart throwsNoSuchElementException
.- Throws:
IllegalStateException
- if the instance is absent (isPresent()
returnsfalse
); depending on this specific exception type (over the more generalRuntimeException
) is discouraged
-
or
Returns the contained instance if it is present;defaultValue
otherwise. If no default value should be required because the instance is known to be present, useget()
instead. For a default value ofnull
, useorNull()
.Note about generics: The signature
public T or(T defaultValue)
is overly restrictive. However, the ideal signature,public <S super T> S or(S)
, is not legal Java. As a result, some sensible operations involving subtypes are compile errors:Optional<Integer> optionalInt = getSomeOptionalInt(); Number value = optionalInt.or(0.5); // error FluentIterable<? extends Number> numbers = getSomeNumbers(); Optional<? extends Number> first = numbers.first(); Number value = first.or(0.5); // error
As a workaround, it is always safe to cast an
Optional<? extends T>
toOptional<T>
. Casting either of the above exampleOptional
instances toOptional<Number>
(whereNumber
is the desired output type) solves the problem:Optional<Number> optionalInt = (Optional) getSomeOptionalInt(); Number value = optionalInt.or(0.5); // fine FluentIterable<? extends Number> numbers = getSomeNumbers(); Optional<Number> first = (Optional) numbers.first(); Number value = first.or(0.5); // fine
Comparison to
java.util.Optional
: this method is similar to Java 8'sOptional.orElse
, but will not acceptnull
as adefaultValue
(orNull()
must be used instead). As a result, the value returned by this method is guaranteed non-null, which is not the case for thejava.util
equivalent. -
or
Returns thisOptional
if it has a value present;secondChoice
otherwise.Comparison to
java.util.Optional
: this method has no equivalent in Java 8'sOptional
class; writethisOptional.isPresent() ? thisOptional : secondChoice
instead. -
or
Returns the contained instance if it is present;supplier.get()
otherwise.Comparison to
java.util.Optional
: this method is similar to Java 8'sOptional.orElseGet
, except whensupplier
returnsnull
. In this case this method throws an exception, whereas the Java 8+ method returns thenull
to the caller.- Throws:
NullPointerException
- if this optional's value is absent and the supplier returnsnull
-
orNull
-
asSet
Returns an immutable singletonSet
whose only element is the contained instance if it is present; an empty immutableSet
otherwise.Comparison to
java.util.Optional
: this method has no equivalent in Java 8'sOptional
class. However, this common usage:
... can be replaced with:for (Foo foo : possibleFoo.asSet()) { doSomethingWith(foo); }
possibleFoo.ifPresent(foo -> doSomethingWith(foo));
Java 9 users: some use cases can be written with calls to
optional.stream()
.- Since:
- 11.0
-
transform
If the instance is present, it is transformed with the givenFunction
; otherwise,absent()
is returned.Comparison to
java.util.Optional
: this method is similar to Java 8'sOptional.map
, except whenfunction
returnsnull
. In this case this method throws an exception, whereas the Java 8+ method returnsOptional.absent()
.- Throws:
NullPointerException
- if the function returnsnull
- Since:
- 12.0
-
equals
Returnstrue
ifobject
is anOptional
instance, and either the contained references are equal to each other or both are absent. Note thatOptional
instances of differing parameterized types can be equal.Comparison to
java.util.Optional
: no differences. -
hashCode
-
toString
-
presentInstances
Returns the value of each present instance from the suppliedoptionals
, in order, skipping over occurrences ofabsent()
. Iterators are unmodifiable and are evaluated lazily.Comparison to
java.util.Optional
: this method has no equivalent in Java 8'sOptional
class; useoptionals.stream().filter(Optional::isPresent).map(Optional::get)
instead.Java 9 users: use
optionals.stream().flatMap(Optional::stream)
instead.- Since:
- 11.0 (generics widened in 13.0)
-