Class Optional<T>
- java.lang.Object
-
- com.google.common.base.Optional<T>
-
- Type Parameters:
T- the type of instance that can be contained.Optionalis naturally covariant on this type, so it is safe to cast anOptional<T>toOptional<S>for any supertypeSofT.
- All Implemented Interfaces:
Serializable
@DoNotMock("Use Optional.of(value) or Optional.absent()") @GwtCompatible(serializable=true) public abstract class Optional<T> extends Object implements Serializable
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 "containnull".A non-null
Optional<T>reference can be used as a replacement for a nullableTreference. It allows you to represent "aTthat must be present" and a "aTthat 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
nullto 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 newOptionalclass 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.Optionalis not. java.util.Optionalhas the additional methodsifPresent,filter,flatMap, andorElseThrow.java.utiloffers the primitive-specialized versionsOptionalInt,OptionalLongandOptionalDouble, 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:
- Serialized Form
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description static <T> Optional<T>absent()Returns anOptionalinstance with no contained reference.abstract Set<T>asSet()abstract booleanequals(Object object)Returnstrueifobjectis anOptionalinstance, and either the contained references are equal to each other or both are absent.static <T> Optional<T>fromJavaUtil(Optional<T> javaUtilOptional)Returns the equivalentcom.google.common.base.Optionalvalue to the givenjava.util.Optional, ornullif the argument is null.static <T> Optional<T>fromNullable(T nullableReference)IfnullableReferenceis non-null, returns anOptionalinstance containing that reference; otherwise returnsabsent().abstract Tget()Returns the contained instance, which must be present.abstract inthashCode()Returns a hash code for this instance.abstract booleanisPresent()Returnstrueif this holder contains a (non-null) instance.static <T> Optional<T>of(T reference)Returns anOptionalinstance containing the given non-null reference.abstract Optional<T>or(Optional<? extends T> secondChoice)Returns thisOptionalif it has a value present;secondChoiceotherwise.abstract Tor(Supplier<? extends T> supplier)Returns the contained instance if it is present;supplier.get()otherwise.abstract Tor(T defaultValue)Returns the contained instance if it is present;defaultValueotherwise.abstract TorNull()Returns the contained instance if it is present;nullotherwise.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().Optional<T>toJavaUtil()Returns the equivalentjava.util.Optionalvalue to this optional.static <T> Optional<T>toJavaUtil(Optional<T> googleOptional)Returns the equivalentjava.util.Optionalvalue to the givencom.google.common.base.Optional, ornullif the argument is null.abstract StringtoString()Returns a string representation for this instance.abstract <V> Optional<V>transform(Function<? super T,V> function)
-
-
-
Method Detail
-
absent
public static <T> Optional<T> absent()
Returns anOptionalinstance with no contained reference.Comparison to
java.util.Optional: this method is equivalent to Java 8'sOptional.empty.
-
of
public static <T> Optional<T> of(T reference)
Returns anOptionalinstance containing the given non-null reference. To havenulltreated asabsent(), usefromNullable(T)instead.Comparison to
java.util.Optional: no differences.- Throws:
NullPointerException- ifreferenceis null
-
fromNullable
public static <T> Optional<T> fromNullable(@CheckForNull T nullableReference)
IfnullableReferenceis non-null, returns anOptionalinstance containing that reference; otherwise returnsabsent().Comparison to
java.util.Optional: this method is equivalent to Java 8'sOptional.ofNullable.
-
fromJavaUtil
@CheckForNull public static <T> Optional<T> fromJavaUtil(@CheckForNull Optional<T> javaUtilOptional)
Returns the equivalentcom.google.common.base.Optionalvalue to the givenjava.util.Optional, ornullif the argument is null.- Since:
- 21.0
-
toJavaUtil
@CheckForNull public static <T> Optional<T> toJavaUtil(@CheckForNull Optional<T> googleOptional)
Returns the equivalentjava.util.Optionalvalue to the givencom.google.common.base.Optional, ornullif the argument is null.If
googleOptionalis known to be non-null, usegoogleOptional.toJavaUtil()instead.Unfortunately, the method reference
Optional::toJavaUtilwill 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
-
toJavaUtil
public Optional<T> toJavaUtil()
Returns the equivalentjava.util.Optionalvalue to this optional.Unfortunately, the method reference
Optional::toJavaUtilwill 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
-
isPresent
public abstract boolean isPresent()
Returnstrueif this holder contains a (non-null) instance.Comparison to
java.util.Optional: no differences.
-
get
public abstract T 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 the Java 8 counterpart throwsNoSuchElementException.- Throws:
IllegalStateException- if the instance is absent (isPresent()returnsfalse); depending on this specific exception type (over the more generalRuntimeException) is discouraged
-
or
public abstract T or(T defaultValue)
Returns the contained instance if it is present;defaultValueotherwise. 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); // errorAs a workaround, it is always safe to cast an
Optional<? extends T>toOptional<T>. Casting either of the above exampleOptionalinstances toOptional<Number>(whereNumberis 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); // fineComparison to
java.util.Optional: this method is similar to Java 8'sOptional.orElse, but will not acceptnullas 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.utilequivalent.
-
or
public abstract Optional<T> or(Optional<? extends T> secondChoice)
Returns thisOptionalif it has a value present;secondChoiceotherwise.Comparison to
java.util.Optional: this method has no equivalent in Java 8'sOptionalclass; writethisOptional.isPresent() ? thisOptional : secondChoiceinstead.
-
or
@Beta public abstract T or(Supplier<? extends T> supplier)
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 whensupplierreturnsnull. In this case this method throws an exception, whereas the Java 8 method returns thenullto the caller.- Throws:
NullPointerException- if this optional's value is absent and the supplier returnsnull
-
orNull
@CheckForNull public abstract T orNull()
Returns the contained instance if it is present;nullotherwise. If the instance is known to be present, useget()instead.Comparison to
java.util.Optional: this method is equivalent to Java 8'sOptional.orElse(null).
-
asSet
public abstract Set<T> asSet()
Returns an immutable singletonSetwhose only element is the contained instance if it is present; an empty immutableSetotherwise.Comparison to
java.util.Optional: this method has no equivalent in Java 8'sOptionalclass. 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
public abstract <V> Optional<V> transform(Function<? super T,V> function)
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 whenfunctionreturnsnull. 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
public abstract boolean equals(@CheckForNull Object object)
Returnstrueifobjectis anOptionalinstance, and either the contained references are equal to each other or both are absent. Note thatOptionalinstances of differing parameterized types can be equal.Comparison to
java.util.Optional: no differences.- Overrides:
equalsin classObject- Parameters:
object- the reference object with which to compare.- Returns:
trueif this object is the same as the obj argument;falseotherwise.- See Also:
Object.hashCode(),HashMap
-
hashCode
public abstract int hashCode()
Returns a hash code for this instance.Comparison to
java.util.Optional: this class leaves the specific choice of hash code unspecified, unlike the Java 8 equivalent.- Overrides:
hashCodein classObject- Returns:
- a hash code value for this object.
- See Also:
Object.equals(java.lang.Object),System.identityHashCode(java.lang.Object)
-
toString
public abstract String toString()
Returns a string representation for this instance.Comparison to
java.util.Optional: this class leaves the specific string representation unspecified, unlike the Java 8 equivalent.
-
presentInstances
@Beta public 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(). Iterators are unmodifiable and are evaluated lazily.Comparison to
java.util.Optional: this method has no equivalent in Java 8'sOptionalclass; 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)
-
-