Core Java

Java 9: Enhancements to Optional

Previously, I wrote about the Optional class that was introduced in Java 8 to model potentially absent values and reduce the number of places where a NullPointerException could be thrown.

Java 9 adds three new methods to Optional:

1. ifPresentOrElse

The new ifPresentOrElse method allows you to perform one action if the Optional is present and a different action if the Optional is not present. For example:

lookup(userId).ifPresentOrElse(this::displayUserDetails,
                               this::displayError)

2. stream

The new stream method makes it easier to convert a stream of Optional objects into a stream of values that are present in them. Previously (in Java 8), you needed two steps in order to achive this. First, you would filter out the empty Optionals and then you would unbox the rest in order to get their values. This is shown below:

// In Java 8:
Stream.of("alice", "bob", "charles")
      .map(UserDirectory::lookup)
      .filter(Optional::isPresent)
      .map(Optional::get)
      .collect(toList());

In Java 9, the code becomes simpler using the stream method:

// In Java 9:
Stream.of("alice", "bob", "charles")
      .map(UserDirectory::lookup)
      .flatMap(Optional::stream)
      .collect(toList());

3. or

The or method is somewhat similar to the orElseGet method but returns Optional objects instead of values. If a value is present, it returns the existing Optional. If the value is not present, it returns the Optional produced by the supplying function. For example:

lookup(userId).or(() -> lookupInAnotherDatabase(userId));
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 9: Enhancements to Optional

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jarrod Roberson
Jarrod Roberson
6 years ago

Optional is a disaster, it just contributes to the null problem, it does not solve it, it just moves it. Do not allow nulls, EVER, in your projects and you never have to deal with the awful hack that is Optional.

Back to top button