Optional
class is introduced in Java 8 to prevent the null checks and
NullPointerException. Before Java 8, if-constructs are used to check the null
values. But, it is not an perfect way to check for null value as it doesn’t resolve
NullPointerException although it just hides it and propagates it to the next
level. Therefore, inspired by other functional programming languages, Optional
class is introduced in Java to handle the null values from Java 8.
Java 9 Optional Class Improvements :
of(), empty(), ofNullable(), get(), ifPresent(), isPresent(), orElse(), orElseGet(), orElseThrow(), map(), flatMap() and filter() are the methods of Java 8 Optional class. Three more methods are added to Optional class from Java 9.
three new methods are added to improve its functionality.
- stream()
- ifPresentOrElse()
- or()
Let’s see these methods
in detail.
ifPresentOrElse() Method :
This
method performs the given action if the value is present in the Optional object. If the value
is absent, performs the given empty-based action.
You can
use this method when you want to perform different actions depending upon the
presence and absence of a value.
|
|
Output
:
Address :
Address_1
No Address
or() Method :
This method returns an Optional object containing the value if the value is present in the given Optional object. If the value is not present, it returns an Optional produced by the supplying function.
This
method is similar to orElse() and orElseGet() which return
unwrapped value where as this method returns the value wrapped in another Optional.
|
|
Output
:
Address_1
No Address
stream() Method :
This
method returns a stream containing the value if the value is present in the
given Optional object.
If the value is not present, it returns an empty stream.
This
method converts Optional into Stream and enables the
developers to use all operations of Stream API with an Optional object also.
|
|
Output
:
Address_1
Our Website Link:: https://cutt.ly/IH9kWsf
ReplyDelete