Optional Class | Guava | Java

Introduction : Optional is 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.

Example : Hashmap.get(key) may return a null when the key is not found in the Hashmap but it may also return a null if the key exists but the value is null. The Optional class can be used where one might use a null object.

The Optional class has no constructors, but provides 3 public static methods for acquiring an instance of the class.

  • Optional.fromNullable(T) allows a null or non-null reference to be provided and wrapped in the new Optional instance.
    • If the passed-in parameter is null, then the instance does not have any reference stored and is an “absent” instance.
    • If the passed-in parameter is not null, then that non-null reference is stored within the new Optional instance.
  • Optional.of(T) which acts like Optional.fromNullable(T), except that it expects a non-null parameter to be passed to it. If null is passed to it, a NullPointerException is thrown.
  • Optional.absent() is useful when one has code that knows the parameter that would have been provided to Optional.fromNullable(T) is null and it is more clear to express than an “absent” version of Optional should be returned.

Once an instance of Optional has been acquired, there are several instance methods that can be called on that instance. For example, Optional.isPresent() method is useful for determining if a given Optional instance has a non-null parameter within it. Once it is known that an Optional instance contains a non-null reference, the Optional.get() method returns that stored non-null reference.

Note : If there is no non-null reference, an exception is thrown upon this method’s invocation. So, it is better to call isPresent() first.

Declaration :

@GwtCompatible(serializable = true)
public abstract class Optional<T>
extends Object
implements Serializable

Where, T is the type of instance that can be contained.

Optional Class Methods :

Example :

// Java code to show implementation of
// Guava Optional class
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Optional;
import static com.google.common.base.Strings.emptyToNull;

class GuavaLibrary {

    // Driver code
    public static void main(String[] args)

        // Creating a List of Strings
        List<String> myList = new ArrayList<String>();

        // Adding values to the Strings
        myList.add("Data Structures");

        // Displaying values using Java Nulls

        // Displaying values using Guava Optional

    // Method to display values using Java Nulls
    public static void displayValuesUsingJavaNulls(List<String> myList)
        System.out.println("Displaying values using Java Nulls");

        // For every String in myList
        for (String str : myList) {

            if (str == null || str.isEmpty()) {
                System.out.println("String : Value is empty or not available");
            else {
                System.out.println("String : " + str);

    // Method to display values using Guava Optional
    public static void displayValuesUsingGuavaOptional(List<String> myList)
        System.out.println("Displaying values using Guava Optional");

        // For each String in myList
        for (String str : myList) {
            Optional<String> optionalName = Optional.fromNullable(emptyToNull(str));
            System.out.println("String : " + optionalName.or("String : Value is empty or not available"));

Output :

Displaying values using Java Nulls
String : Geeks
String : for
String : GeeksClasses
String : Value is empty or not available
String : GeeksforGeeks
String : Value is empty or not available
String : Data Structures

Displaying values using Guava Optional
String : Geeks
String : for
String : GeeksClasses
String : String : Value is empty or not available
String : GeeksforGeeks
String : String : Value is empty or not available
String : Data Structures

Below given are some other methods provided by Guava Optional Class :

Guava Optional Class Vs java.util.Optional

  • Guava Optional class is serializable, but java.util.Optional is not.
  • java.util.Optional has the additional methods ifPresent, filter, flatMap, and orElseThrow.
  • java.util.Optional offers the primitive-specialized versions OptionalInt, OptionalLong and OptionalDouble but Guava does not have these.

Reference : Google Guava

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

4 Average Difficulty : 4/5.0
Based on 1 vote(s)