Post Brief Table of Content:
- Introduction
- Java SE 8: Optional Class Basics
- Java SE 8: Optional Basic Example
- Java SE 9: Optional Class Improvements
- Java SE 9: Optional stream() Method
- Java SE 8 Style: Optional Methods
- Java SE 9: Optional ifPresentOrElse() Method
- Java SE 9: Optional or() Method
Introduction
In this post, we are going to discuss about “How Java SE 8’s Optional class solves null check problem?” and also “Java SE 9’s Optional class improvements”.
As a Java Developer, we know how much work we used to do for null checks for each and every object to avoid NullPointerException errors.
Java SE 8: Optional Class Basics
Oracle Corp has introduced Optional class as part of “java.util” package. It is a container object which may or may not contain a non-null value.
It is mainly used to avoid lot of null checks and NullPointerException issues. Even though is part of java.util package, but it does NOT implement any Collection API interfaces. It extends Object class as shown below.
1 2 3 |
public final class Optional<T> extends Object |
It is final class and we cannot override it. If Optional object is NOT empty, that means a value is present in it. If it is empty, then a value is absent as shown below.
Java SE 8: Optional Basic Example
In this section, we will explore on how to use Java SE 8 Optional object to avoid null checks and NullPointerExceptions.
Example:-
It is simple and basic example on Optional class. It demonstrates how to create an empty Optional object using Optional.empty() and how to create non-empty Optional object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Optional; public class JavaSE8OptionalDemo { public static void main(String[] args) { System.out.println(division(4,2)); System.out.println(division(4,0)); } public static Optional<Integer> division(Integer i1,Integer i2) { if(i2 == 0) return Optional.empty(); else { Integer i3 = i1/i2; return Optional.of(i3); } } } |
Outuput:-
1 2 3 4 |
<span style="color: #008000;"><strong><code> Optional[2] Optional.empty </code></strong></span> |
Java SE 9: Optional Class Improvements
In Java SE 9, Oracle Corp has introduced the following three methods to improve Optional functionality.
- stream()
- ifPresentOrElse()
- or()
We will pick up these methods one by one and discuss in-detail with some suitable examples in the coming sections.
Java SE 9: Optional stream() Method
If a value present in the given Optional object, this stream() method returns a sequential Stream with that value. Otherwise, it returns an Empty Stream.
They have added “stream()” method to work on Optional objects lazily as shown below:
1 2 3 4 |
Stream<Optional> emp = getEmployee(id) Stream empStream = emp.flatMap(Optional::stream) |
Here Optional.stream() method is used convert a Stream of Optional of Employee object into a Stream of Employee so that we can work on this result lazily in the result code.
Java SE 8 Style: Optional Methods
In Java SE 8, we should use ifPresent(), isPresent(), orElse() etc. methods to check an Optional object and perform some functionality on it. It’s bit tedious process to perform this. However, Java SE 9 has introduced a new method to overcome this problem.
Let us explore Java SE 8 style in this section. We will explore that new method in next section.
Here we are going to explore the following three Optional class methods:
1 2 3 |
void ifPresent(Consumer action) |
If a value is present, performs the given action with the value, otherwise does nothing.
- isPresent()
1 2 3 |
boolean isPresent() |
If a value is present, returns true, otherwise false.
- orElse()
1 2 3 |
public T orElse(T other) |
If a value is present, returns the value, otherwise returns other.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Optional; public class JavaSE8OptionalDemo { public static void main(String[] args) { Optional<Integer> opt1 = division(4,2); opt1.ifPresent( x -> System.out.println("Option1: Result found = " + x)); Optional<Integer> opt2 = division(4,0); opt2.ifPresent( x -> System.out.println("Option2: Result found: " + x)); System.out.println("Option2: Result not found, default vlaue = " + opt2.orElse(new Integer(0))); if(opt2.isPresent()) System.out.println("Option2: Result found."); else System.out.println("Option2: Result not found."); } public static Optional<Integer> division(Integer i1,Integer i2) { if(i2 == 0) return Optional.empty(); else { Integer i3 = i1/i2; return Optional.of(i3); } } } |
Outuput:-
1 2 3 4 5 |
<span style="color: #008000;"><strong><code> Option1: Result found = 2 Option2: Result not found, default vlaue = 0 Option2: Result not found. </code></strong></span> |
Java SE 9: Optional ifPresentOrElse() Method
In section, we explore same kind of scenarios by using Java SE 9’s Optional ifPresentOrElse() Method. It combines all those methods like ifPresent(), isPresent() and orElse() methods in a nice way.
Java SE 9 Optional ifPresentOrElse() API:-
1 2 3 |
public void ifPresentOrElse(Consumerl<? super Tl> action, Runnable emptyAction) |
If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
ifPresentOrElse() Example:-
1 2 3 4 5 6 7 8 9 10 |
jshell> Optional<Integer> opt1 = Optional.of(4) opt1 ==> Optional[4] jshell> opt1.ifPresentOrElse( x -> System.out.println("Result found: " + x), () -> System.out.println("Not Found.")) Result found: 4 jshell> Optional<Integer> opt2 = Optional.empty() opt2 ==> Optional.empty jshell> opt2.ifPresentOrElse( x -> System.out.println("Result found: " + x), () -> System.out.println("Not Found.")) Not Found. |
Java SE 9: Optional or() Method
In Java SE 9 Optional API, or() method is used to return a value, if Optional contains a value. Otherwise returns a value specified in the Supplier. This or() method takes a Supplier as an argument to specify a default value
Java SE 9 Optional or() API:-
1 2 3 |
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) |
Let us see an example with a value present in Optional first.
Java SE 9 Optional or() Example-1:-
1 2 3 4 5 6 7 8 9 |
jshell> Optional<String> opStr = Optional.of("Rams") opStr ==> Optional[Rams] jshell> import java.util.function.* jshell> Supplier<Optional<String>> supStr = () -> Optional.of("No Name") supStr ==> $Lambda$67/222624801@23faf8f2 jshell> opStr.or(supStr) $5 ==> Optional[Rams] |
Let us see an example with a value not-present in Optional now.
Java SE 9 Optional or() Example-2:-
1 2 3 4 5 6 7 8 |
jshell> Optional<String> opStr = Optional.empty() opStr ==> Optional.empty jshell> Supplier<Optional<String>> supStr = () -> Optional.of("No Name") supStr ==> $Lambda$67/222624801@23faf8f2 jshell> opStr.or(supStr) $7 ==> Optional[No Name] |
That’s it all about “Java SE 9: Optional Class Improvements” new feature. We will discuss some more Java SE 9 New Features in my coming posts.
Please drop me a comment if you like my post or have any issues/suggestions/type errors.
Thank you for reading my tutorials.
Happy Java SE 9 Learning!