Top Description Fields Constructors Methods
com.google.common.base

public abstract Class Optional<T>

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Known Direct Subclasses
com.google.common.base.Present, com.google.common.base.Absent
Annotations
@DoNotMock:Use Optional.of(value) or Optional.absent()
@GwtCompatible
serializable:true
@ElementTypesAreNonnullByDefault
Type Parameters
<T>
the type of instance that can be contained. Optional is naturally covariant on this type, so it is safe to cast an Optional<T> to Optional<S> for any supertype S of T.
Static Imports
com.google.common.base.Preconditions.checkNotNull

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<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

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.

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.

Authors
Kurt Alfred Kluever, Kevin Bourrillion
Since
10.0

Field Summary

Modifier and TypeField and Description
private static final long

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public static <T> Optional<T>
absent()

Returns an Optional instance with no contained reference.

public abstract Set<T>
asSet()

Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise.

public abstract boolean
equals(Object
the reference object with which to compare.
object
)

Overrides java.lang.Object.equals.

Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent.
public static <T> Optional<T>
fromJavaUtil(Optional<T> javaUtilOptional)

Returns the equivalent com.google.common.base.Optional value to the given java.util.Optional, or null if the argument is null.

public static <T> Optional<T>
fromNullable(T nullableReference)

If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns Optional#absent.

public abstract T
get()

Returns the contained instance, which must be present.

public abstract int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code for this instance.
public abstract boolean
isPresent()

Returns true if this holder contains a (non-null) instance.

public static <T> Optional<T>
of(T reference)

Returns an Optional instance containing the given non-null reference.

public abstract T
or(T defaultValue)

Returns the contained instance if it is present; defaultValue otherwise.

public abstract Optional<T>
or(Optional<? extends T> secondChoice)

Returns this Optional if it has a value present; secondChoice otherwise.

public abstract T
or(Supplier<? extends T> supplier)

Returns the contained instance if it is present; supplier.get() otherwise.

public abstract T
orNull()

Returns the contained instance if it is present; null otherwise.

public static <T> Iterable<T>
presentInstances(final Iterable<? extends Optional<? extends T>> optionals)

Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of Optional#absent.

public static <T> Optional<T>
toJavaUtil(Optional<T> googleOptional)

Returns the equivalent java.util.Optional value to the given com.google.common.base.Optional, or null if the argument is null.

public Optional<T>
toJavaUtil()

Returns the equivalent java.util.Optional value to this optional.

public abstract String
toString()

Overrides java.lang.Object.toString.

Returns a string representation for this instance.
public abstract <V> Optional<V>
transform(Function<? super T, V> function)

If the instance is present, it is transformed with the given Function; otherwise, Optional#absent is returned.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

serialVersionUIDback to summary
private static final long serialVersionUID

Constructor Detail

Optionalback to summary
pack-priv Optional()

Method Detail

absentback to summary
public static <T> Optional<T> absent()

Returns an Optional instance with no contained reference.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.empty.

asSetback to summary
public abstract Set<T> asSet()

Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise.

Comparison to java.util.Optional: this method has no equivalent in Java 8's Optional class. However, this common usage:

for (Foo foo : possibleFoo.asSet()) {
  doSomethingWith(foo);
}
... can be replaced with:
possibleFoo.ifPresent(foo -> doSomethingWith(foo));

Java 9 users: some use cases can be written with calls to optional.stream().

Since
11.0
equalsback to summary
public abstract boolean equals(Object object)

Overrides java.lang.Object.equals.

Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent. Note that Optional instances of differing parameterized types can be equal.

Comparison to java.util.Optional: no differences.

Parameters
object:Object

Doc from java.lang.Object.equals.

the reference object with which to compare.

Returns:boolean

Doc from java.lang.Object.equals.

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
fromJavaUtilback to summary
public static <T> Optional<T> fromJavaUtil(Optional<T> javaUtilOptional)

Returns the equivalent com.google.common.base.Optional value to the given java.util.Optional, or null if the argument is null.

Annotations
@CheckForNull
Since
21.0
fromNullableback to summary
public static <T> Optional<T> fromNullable(T nullableReference)

If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns Optional#absent.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.ofNullable.

getback to summary
public abstract T get()

Returns the contained instance, which must be present. If the instance might be absent, use or(Object) or orNull instead.

Comparison to java.util.Optional: when the value is absent, this method throws IllegalStateException, whereas the java.util counterpart throws NoSuchElementException.

Exceptions
IllegalStateException:
if the instance is absent (isPresent returns false); depending on this specific exception type (over the more general RuntimeException) is discouraged
hashCodeback to summary
public abstract int hashCode()

Overrides java.lang.Object.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.

Returns:int

Doc from java.lang.Object.hashCode.

a hash code value for this object

Annotations
@Override
isPresentback to summary
public abstract boolean isPresent()

Returns true if this holder contains a (non-null) instance.

Comparison to java.util.Optional: no differences.

ofback to summary
public static <T> Optional<T> of(T reference)

Returns an Optional instance containing the given non-null reference. To have null treated as absent, use fromNullable instead.

Comparison to java.util.Optional: no differences.

Exceptions
NullPointerException:
if reference is null
orback to summary
public abstract T or(T defaultValue)

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, use get() instead. For a default value of null, use orNull.

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> to Optional<T>. Casting either of the above example Optional instances to Optional<Number> (where Number 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's Optional.orElse, but will not accept null as a defaultValue (orNull must be used instead). As a result, the value returned by this method is guaranteed non-null, which is not the case for the java.util equivalent.

orback to summary
public abstract Optional<T> or(Optional<? extends T> secondChoice)

Returns this Optional if it has a value present; secondChoice otherwise.

Comparison to java.util.Optional: this method has no equivalent in Java 8's Optional class; write thisOptional.isPresent() ? thisOptional : secondChoice instead.

orback to summary
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's Optional.orElseGet, except when supplier returns null. In this case this method throws an exception, whereas the Java 8+ method returns the null to the caller.

Exceptions
NullPointerException:
if this optional's value is absent and the supplier returns null
orNullback to summary
public abstract T orNull()

Returns the contained instance if it is present; null otherwise. If the instance is known to be present, use get() instead.

Comparison to java.util.Optional: this method is equivalent to Java 8's Optional.orElse(null).

Annotations
@CheckForNull
presentInstancesback to summary
public static <T> Iterable<T> presentInstances(final Iterable<? extends Optional<? extends T>> optionals)

Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of Optional#absent. Iterators are unmodifiable and are evaluated lazily.

Comparison to java.util.Optional: this method has no equivalent in Java 8's Optional class; use optionals.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)
toJavaUtilback to summary
public static <T> Optional<T> toJavaUtil(Optional<T> googleOptional)

Returns the equivalent java.util.Optional value to the given com.google.common.base.Optional, or null if the argument is null.

If googleOptional is known to be non-null, use googleOptional.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 expression o -> Optional.toJavaUtil(o) instead.

Annotations
@CheckForNull
Since
21.0
toJavaUtilback to summary
public Optional<T> toJavaUtil()

Returns the equivalent java.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 expression o -> o.toJavaUtil() instead.

Since
21.0
toStringback to summary
public abstract String toString()

Overrides java.lang.Object.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.

Returns:String

Doc from java.lang.Object.toString.

a string representation of the object

Annotations
@Override
transformback to summary
public abstract <V> Optional<V> transform(Function<? super T, V> function)

If the instance is present, it is transformed with the given Function; otherwise, Optional#absent is returned.

Comparison to java.util.Optional: this method is similar to Java 8's Optional.map, except when function returns null. In this case this method throws an exception, whereas the Java 8+ method returns Optional.absent().

Exceptions
NullPointerException:
if the function returns null
Since
12.0