Introduction to Optional class in Java

Optional is a public final class introduced as part of Java 8 to represent a non-null value. It is located in java.util package.
Using the Optional class, we can avoid NullPointerException and unnecessary null checks.

How to create an Optional in Java?

We can create an Optional in three ways:

  1. Optional.empty() method – It returns an empty Optional object. No value is present for this Optional.
  2. Optional.of(T value) method – It returns an Optional with the specified present non-null value.
  3. Optional.ofNullable(T value) – It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.


1. Optional.empty() method

class Test {

  public static void main(String[] args) {
    Optional optional = Optional.empty(); // creates an empty Optional

    if (optional.isEmpty()) {
      System.out.println("It is an empty Optional.");
    } else {
      System.out.println("Optional is not empty.");
    }
  }
}

Output: It is an empty Optional.


2. Optional.of(T value) method

class Test {

  public static void main(String[] args) {
    Optional optional = Optional.of("STRING VALUE"); // creates an Optional that will hold the specified value

    if (optional.isEmpty()) {
      System.out.println("It is an empty Optional.");
    } else {
      System.out.println("Optional is not empty.");
      // get the value from the Optional
      System.out.println(optional.get());
    }
  }
}

Output: Optional is not empty. STRING VALUE


3. Optional.ofNullable(T value)

class Test {

  public static void main(String[] args) {
    String value = "someValue";
    Optional optional = Optional.ofNullable(value); // passed the non-null value

    if (optional.isEmpty()) {
      System.out.println("It is an empty Optional.");
    } else {
      System.out.println("Optional is not empty.");
      // get the value from the Optional
      System.out.println(optional.get());
    }

    System.out.println();

    String value2 = null;

    Optional optional2 = Optional.ofNullable(value2); // passed the null value

    if (optional2.isEmpty()) {
      System.out.println("It is an empty Optional.");
    } else {
      System.out.println("Optional is not empty.");
    }
  }
}

Output: Optional is not empty. someValue It is an empty Optional.


How to get the value from the Optional?

To get the value, we use the get() method. If a value is present in the Optional, it will be returned. Otherwise it throws NoSuchElementException.

Considering this, we should always first check if the value is present or not:

class Test {

  public static void main(String[] args) {
    Optional<String> optional = Optional.ofNullable("someValue");

    if (optional.isPresent()) { // check if it's an empty Optional
      System.out.println("The value is: " + optional.get()); // get the value from the Optional
    } else {
      System.out.println("Optional is empty.");
    }
  }
}

Output: The value is: someValue


Some of the most used methods from the Optional class:

Methods Description
public T get() If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
public boolean isPresent() It returns true if there is a value present, otherwise false.
public void ifPresent(Consumer<? super T> consumer) If a value is present, invoke the specified consumer with the value, otherwise do nothing.
public Optional<T> filter(Predicate<? super T> predicate) If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
public <U> Optional<U> map(Function<? super T,? extends U> mapper) If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise, return an empty Optional.
public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper) If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
public T orElse(T other) It returns the value if present, otherwise returns other.
public T orElseGet(Supplier<? extends T> other) It returns the value if present, otherwise invoke other and return the result of that invocation.
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier.
public boolean equals(Object obj) Indicates whether some other object is “equal to” this Optional or not. The other object is considered equal if:
  • It is also an Optional
  • Both instances have no value present
  • the present values are “equal to” each other via equals().
public int hashCode() It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present.
public String toString() It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions.


In the next lessons, we will cover all of them in detail.

Happy coding!

 

Leave a Reply

Your email address will not be published.