Java 9 Improved Optional Class
The Optional class was introduced in Java 8. The introduction of the Optional class effectively solves the null pointer exception. In Java 9, three methods were added to improve its functionality:
- stream()
- ifPresentOrElse()
- or()
stream() method
Syntax
public Stream<T> stream()
The stream method converts an Optional into a Stream. If the Optional contains a value, it returns a Stream containing that value; otherwise, it returns an empty Stream (Stream.empty()).
Example
Executing the output result is:
[A, B] [A, B]
ifPresentOrElse() method
Syntax
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
The improvement of the ifPresentOrElse method is that it has an else, accepting two parameters: Consumer and Runnable.
The purpose of the ifPresentOrElse method is: if an Optional contains a value, the function action is called on the contained value, i.e., action.accept(value), which is consistent with ifPresent; the difference from the ifPresent method is that ifPresentOrElse also has a second parameter, emptyAction — if the Optional does not contain a value, ifPresentOrElse calls emptyAction, i.e., emptyAction.run().
Example
Executing the output result is:
Value: 1 Not Present.
or() method
Syntax
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
If a value exists, return the value specified by Optional; otherwise, return a preset value.
Example
Executing the output result is:
Value: Mahesh Value: Not Present
Java 9 New Features