This tutorial is going to cover about new methods of the Optional<T> class in Java 9. We’re going to get through 3 methods which recently added, have the syntax as follows:

  • void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
  • Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
  • Stream<T> stream()

For more detail about the Optional<T> class, please visit its Javadocs on Oracle web site.

1. The stream() Method

The stream() method has been added to the Option<T> class from Java 9.When we call the method on an Optional object, if a value is present it returns a sequential Stream containing only that value, otherwise, returns an empty Stream.

Let’s see ist syntax as follows:

And examples:

2. The ifPresentOrElse() Method

Firstly, let’s take a look again at the syntax of the ifPresentOrElse() method:

Parameters:

  • action:  the action to be performed, if a value is present.
  • emptyAction:  the empty-based action to be performed, if no value is present.

Next, let’s see some examples:

Firstly, we define a list of days which contains 7 days, the 3rd, 4th elements are empty or NULL.

And next, we leverage Java Stream API to print out the list.  The ifPresentOrElse() provides us two alternatives actions for both cases: data presents and data is NULL or empty. Running the example will give the result as follows:

3. The or() Method

Let’s take a look at the or(),  a new method of the Optional<T> class introduced in Java 9:

Parameters:

  • supplier – the supplying function that produces an Optional to be returned

The method returns an Optional describing the value of this Optional, if a value is present, otherwise an Optional produced by the supplying function.

Let’s see an example:

Firstly, we create a list of ages of students in a class with several students whose ages are not clear, is NULL or empty. Next, we will replace all those students (whose ages are not clear) by a default age 20 and then print out.

Running the example will print out the result:

4. Conclusions

The tutorial has illustrated how to use the new methods of the Optional<T> class in Java 9. Those methods are useful for us in manipulating with the Option<T> class, especially with Stream API.

Below are other Java 9 related tutorials for your references:

Java 9 Tutorial

Java 9 JShell Cheat Sheet

Install Oracle Java 9 on CentOS, RHEL 7

Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)

Set Up Eclipse, IntelliJ And NetBeans For Java 9

Create Immutable Lists In Java 9 By Static Factory Methods

Private Interface Methods In Java 9

Using The InputStream.transferTo() To Copy Streams In Java 9

Streams API Updates In Java 9

How To Compare Arrays In Java 9

Java 9 HTTP 2 Client API Example

Java 9 – Effectively Final Variables In try-with-resources

0 0 vote
Article Rating