Java8 Bliss: Optional

Table of contents
Reading Time: 5 minutes

Java8 is not so new now. Everybody is well aware and probably using it in one or the other project. Certainly, Java8 is a big leap for Java since it makes Java functional.
(though its procedural internally). Anyway, it successfully got interested in the IT industry.

In this blog, I am going to talk about one of the vital features of Java8 i.e. Optional. Optional, as the name suggests gives an option to use/operate on the value. Let’s dive deep into the world of Optional.
Optional is basically a container object which may or may not have the Not-Null value. It is used for representing a value. The main use of the Optional class is to avoid “NullPointerException“.

Optional is part of the java.util package, so we need to create this import:

How to create Optional Object?

There are several ways of creating Optional objects.
Empty Optional Object :

Optional Object with Static value :

Advantages of Optional in Java 8 :

• There is no need for Null checks.
• No more chances for NullPointerException at runtime.
• No boilerplate in the code (neat and clean code).

Let’s go through the methods used with the optional :
empty(): It returns an empty optional instance.
Syntax : public static Optional empty()

Of(): It returns an optional instance with non-null value.
Syntax : public static Optional of(T value)

ofNullable(): If the value is present in the optional then return the not-null value, otherwise returns an empty optional instance.
Syntax : public static Optional ofNullable(T value)

get(): If the value is present in the optional then return the not-null value, otherwise throws NoSuchElementException.
NOTE: We should not use get method. As it deals only with one side of the value.
Syntax : public T get()

isPresent(): It returns a boolean value. (True or False) If the value is present then true otherwise false.
Syntax : public boolean isPresent()

ifPresent(): If the value is present, invoke the customer with the provided value otherwise do nothing.
Syntax : public void ifPresent(Customer consumer)

filter(): If a value is present, and the value matches the given predicate, return an optional describing the value, otherwise return an empty optional.
Syntax : public Optional filter(Predicate predicate)

map(): If the value is present then map the mapping provided to it, otherwise return the empty Optional.
Syntax: public Optional map(Function mapper)

flatMap(): It is similar to map, the only difference is that flatMap does not wrap it with an additional Optional.
Syntax : public Optional flatMap(Function<? super T,Optional>mapper)

orElse(): Return the value if the value is present , otherwise return the default value.
Syntax : public T orElse(T other)

orElseGet(): Return the value if the value is present, otherwise invoke other and return the result of that invocation.
Syntax: public T orElseGet(Supplier other)

NOTE: orElse() always calls the subsequent function whether you want it or not.Whereas in case of orElseGet() the execution is done if the value is empty.

orElseThrow(): Return the value if the value is present, otherwise throw the exception corresponding to the provided supplier.
Syntax : public T orElseThrow(Supplier exceptionSupplier)throws X extends Throwable

equals(): It returns true or false on the basis of the condition that the two object are equal or not. And two objects here, are equal when :
1. it is also an Optional and;
2. both instances have no value present or;
3. the present values are “equal to” each other via equals().
Syntax : public boolean equals(Object obj)

Key Points :
Instance fields – Use plain values. Optional wasn’t created for usage in fields. It’s not serializable and adds a wrapping overhead that you don’t need. Instead, use them on the method when you process the data from the fields.
Method parameters – Use plain values. Dealing with tons of Optionals pollutes the method signatures and makes the code harder to read and maintain. All functions can be lifted to operate on optional types where needed. Keep the code simple!
Method return values – Consider using Optional. Instead of returning nulls, the Optional type might be better. Whoever uses the code will be forced to handle the null case and it makes the code cleaner.
If we pass null to the Optional.ofNullable(), then it doesn’t throw an exception. It actually returns an empty Optional object.

In this blog, we briefly touched upon Java optional – definitely one of the most interesting Java 8 features.

There are much more advanced examples of using optional; the goal of this blog was only to provide a quick and practical introduction to what you can start doing with the functionality and as a starting point for exploring and further learning.
Demo :
https://gist.github.com/Aayush-Aggarwal/b0047c1793bbbe03ed3ac4a64d972b91

References :
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Pasted image at 2017_11_27 04_17 PM

Written by 

Ayush Aggarwal is a Software Consultant having experience of more than 11 months. He has knowledge of various programming languages such as JAVA, C and C++, and also has good knowledge of database technologies like MySQL. He has worked upon Object Oriented Paradigm and a Java and Android enthusiast. His hobbies include playing football, basketball etc.