Java 9 Optional Improvements

Java 9 Optional comes with some small useful improvements. In this tutorial, we’re gonna look at new added methods: stream(), ifPresentOrElse() and or().

I. New Optional API
1. stream()

With Java 8, this is a way for getting a List of Values from a Stream of Optionals:

But, if streamOptional() returns a Stream that contains an empty Optional instance. It will throw a java.util.NoSuchElementException.
To handle this case, we can add filter() method:

Java 9 provides new Optional::stream to work on Optional objects lazily, it returns a stream of either zero or one/more elements. It also checks empty element automatically and removes it.

2. ifPresentOrElse()

Java 8 Optional provides ifPresent() method to perform the given action if a value is present, otherwise do nothing.

We can also use isPresent() and orElse() to make code more clearlier and handle “else” case:

With Java 9, those things are neater by using ifPresentOrElse() method:

This is how the method works:

3. or()

or() method checks if a value is present, it will return an Optional for the value, otherwise return another Optional which is produced by the supplying function.

For example, we can use very cool chain of or() methods like this:

II. Source Code

Run the code, this is result:

Related Posts

Got Something To Say:

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