Guava Optional Class - Guava

What is Guava optional class?

Optional class is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values.

Class Declaration

Following is the declaration for<T> class:

Class Methods


Method & Description


static <T> Optional<T> absent()

Returns an Optional instance with no contained reference.


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.


abstract boolean equals(Object object)

Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent.


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

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


abstract T get()

Returns the contained instance, which must be present.


abstract int hashCode()

Returns a hash code for this instance.


abstract boolean isPresent()

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


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

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


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

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


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

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


abstract T or(T defaultValue)

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


abstract T 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 supplied optionals, in order, skipping over occurrences of absent().


abstract String toString()

Returns a string representation for this instance.


abstract <V> Optional<V> transform(Function<? super T,V> function)

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

Methods Inherited

This class inherits methods from the following class:

  • java.lang.Object

Example of Optional class

Create the following java program using any editor of your choice in say C:/> Guava.

Verify the Result

Compile the class using javac compiler as follows:

Now run the GuavaTester to see the result.

See the result.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Guava Topics