Core Java

Java 8 Optional

Introduction:

java.util.Optional class defined in Java 8 can be thought of as a container class for storing and handling not – null objects. When working with an Optional, a null value is usually represented as an absent value instead.

The Optional class exposes various methods to help us treat values as either ‘Available’ or ‘Unavailable’. It helps in avoiding all the NullPointerException related checks in our code, making it look cleaner.

Class Signature:

java.util.Optional is a final class:

Methods Exposed:

Let’s explore the methods available in the Optional class.

  1. empty(): 

    static method which returns an empty Optional.

  2. isPresent():

    Returns true, if an Optional value is present, false otherwise.

  3. ifPresent(Consumer consumer):

    If Optional is present, this method Invokes a consumer passing in the Optional value.

  4. of() and ofNullable():

    These methods help us instantiate an Optional.

    ofNullable() method accepts both null and not-null Optional values as an input. If a null value is passed, it creates an empty Optional.

  5. get():

    Returns the Optional value, if present. Throws a NoSuchElementException for an empty Optional.

  6. orElse(T other) and orElseGet(Supplier other):

    When we’re not sure if our Optional is empty or not, it isn’t a good idea to use get() method directly. We can rather use orElse() and orElseGet() methods.

    For an empty Optional, orElse() returns the value passed to it as an argument. Similarly, for an empty Optional, orElseGet() method returns the value received from the Supplier method passed in as an argument.

  7. orElseThrow():

    Returns Optional value if present. Throws an exception otherwise.

  8. filter(Predicate predicate): 

    Returns the Optional as is, if the condition specified as the predicate is met. Or else returns an empty Optional.

  9. map() and flatMap():

    map() accepts a mapper function which transform the element to a different type. If a mapper function returns an Optional itself, we can use flatMap() method. It helps us avoid dealing with Optional<Optional<R>> by flattening the result into an Optional<R>.

    To understand the difference between map() and flatMap() method, read this article.

Conclusion:

In this tutorial, we covered Java 8 Optional class in detail. We also learned using most of the methods exposed in an Optional class.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *