Monday, December 25, 2017

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));

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.