Java Optional With Examples

In this article, we’ll explore Java Optional class which was introduced in Java 8.

Java Optional

  • One of the most frequently exception in java programming is NullPointerException. A Null value often represents an absence of value which has to be handled before proceeding with the usual business logic, which leads to unnecessary null checks.
  • To handle such boiler plate code for null check situations, Java 8 introduced Optional class. In this article, we’ll look into details how Java 8 Optional class API helps us to deal with null values.
  • Java 8 stream API and collection methods can return Optional objects. It may or may not contain a non-null value. There are various methods available in the API to deal with the Optional value in a convenient and reliable manner.
  • Java Optional is a final class.
  • Optional-1

Java 8 Optional Example

Let’s look at an example to get the clear idea when it would be helpful to use the objects of Optional class.

Output:

As we can see, we want to filter the list of strings and get a value whose length is greater than a threshold value.

Such values may or may not exist in the list. Optional API would be a perfect choice to use in such situations. As you can see it has ifPresent method which lets us define what to do with the value, if we get any.

In our case, veryLargeString will not contain any value so nothing will get printed.

Java 8 Optional API provides several such methods. In the next sections, we’ll explore them in detail.

Java Optional Methods

  1. static Optional empty(): It creates and returns an empty Optional instance.
  2. boolean isPresent(): It return true if there is a value present, otherwise false.

  3. void ifPresent(Consumer consumer): If a value is present, this method invokes the specified consumer with the value, otherwise does nothing. As we can see, in our first example:

    gave output:
  4. T get(): If a value is present in the Optional, this method returns the value, otherwise throws NoSuchElementException. As you might have gussed

    will also print
  5. T orElse(T otherValue): This method returns the value if present, otherwise returns the otherValue provided in the argument. When we are not sure whether Optional will contain value, it’s always good idea to use this method rather than simple get().

    will print:

    There is also orElseGet(Supplier other) method available, which calls supplier function or executes lambda to get the value instead of returning hard coded value.

    will also print the same value.
  6. static Optional<T> of(T value): It returns an Optional with the specified present non-null value.
  7. Optional filter(Predicate predicate): It takes a predicate as an argument and returns an Optional object. If condition of the predicate is met, then the Optional is returned as is, Otherwise it will return an empty Optional.

    Output:

There are also equals(), hashcode() and toString() methods available in the Optional API.

Java 9 Optional Class enhancements

Java 9 introduced few extra methods in Optional class:

  1. public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction): If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
  2. public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
  3. public Stream<T> stream(): If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.

That’s all for the Java Optional class. You should also check out java 8 features.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: