Introduction
Java 8 Optional class was added in Java 8 release under java.util package. Java 8 Optional is used to represent Optional object or empty value instead null reference.
This will help to avoid null pointer exception which occurs when we try to perform some operation on null reference object. It works as container or wrapper for actual value which may or may not have null. We will see how to use java optional with example.
Why java.util.Optional?
While developing any application or program every developer has faced NullPointerException. Consequently, in order to avoid that null pointer we need to add null checks which could require nesting of if statements. As a result leading to ugly and unreadable code.
Let's look at the following example for better insight:
This code could lead to null pointer if person or person's account does not exist
we can handle this in the following ways, we shall get into details of second way later in this blog.
Double balance = 0.0;
if(person != null ){
Account account = person.getAccount();
if(account != null){
balance = account.getBalance();
}
}
Double balance = person.flatMap(Person::getAccount)
.flatMap(Account::getBalance)
.orElse(0.0);
Up till now we have understood that Optional class helps in avoiding null pointer scenarios. We will learn about different operations we can perform on java 8 Optional object with example.
Methods in Java 8 Optional class
Now, let us look at the different methods present in Optional class, for more details click on the links
A) Ways to create optional:
A most noteworthy point about Optional class is that it has private constructor so we can not create object using new keyword.
First of all, we can create object of Optional class in either of the 3 different ways
- empty(): static method which returns empty optional instance
- of(T value) : static method which returns optional instance of specified value
- ofNullable(T value) : static method which returns optional instance of specified value if value is not null else returns empty instance
B) Ways to check value in optional:
Some times we need to check if optional contains the expected value or not, we can check if optional object contains value or not in 2 ways
- isPresent() : public method which returns true or false depending on value present or not
- filter(Predicate<? super T> predicate): public method which returns optional of value if matches the condition else gives empty optional
C) Ways to get value:
Optional class provides different ways to get values depending on requirement and scenario
- get() : public method which returns the value if present. throws NoSuchElementException if empty
- orElse(T other) : public method which returns the value if present else return 'other' value. Used to specify default value or null if no value present
- orElseGet( Supplier<? extends T> other) : public method which returns the value if present else returns the return value of other. other is functional interface
- orElseThrow(Supplier exceptionSupplier) : public method which returns the value if present else throws exception. used to throw custom exception if value not present
D) Action if data present:
There are many scenarios when we need to perform some operation on data
- ifPresent( Consumer<? super T> consumer): public method used to perform some operation if data is present
- map( Function<? super T,? extends U> mapper): public method is used for mapping of object from one form to another if not empty, returns the optional of new value
- flatMap( Function<? super T Optional<U>> mapper): public method is used for mapping of object from one form to another if not empty however it avoid the nesting of optional
E) Other methods in Optional:
- equals(Object obj): Compares 2 Optional objects, returns true if they are equal else returns false.
- hashCode():Returns the hash code value of the value if present or 0 (zero) if no value is present.
- toString():Returns a non-empty string representation of this Optional object
Fast track reading :
- Added in Java 8 release under java.util package.
- Represent Optional object or empty value instead null reference.
- Optional class has private constructor so we can not create object using new keyword.
Create instance | Check value | Fetch value | Operational methods |
---|---|---|---|
empty() | isPresent() | get() | ifPresent(Consumer consumer) |
of(T value) | filter(Predicate predicate) | orElse(T other) | map(Function mapper) |
ofNullable(T value) | orElseGet(Supplier other) | flatMap(Function mapper) | |
orElseThrow(Supplier exception) |
Thanks for the blog this is very helpful. The Content is presented very well and explained in very proper way.
Thank you very much for taking time to read and appreciate the efforts. This motivates us to keep up our work!! Stay tuned for more such interesting blogs. Hope you like them as well!!