Admin

Java 8 Optional in details with example

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

Double balance = person.getAccount().getBalance();

we can handle this in the following ways, we shall get into details of second way later in this blog.

//Traditional method of handling null
Double balance = 0.0;
if(person != null ){

Account account = person.getAccount();

if(account != null){

balance = account.getBalance();

}

}

// java 8 optional example to handle null
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

  1. empty(): static method which returns empty optional instance
  2. of(T value) : static method which returns optional instance of specified value
  3. 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

  1. isPresent() : public method which returns true or false depending on value present or not
  2. 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

  1. get() : public method which returns the value if present. throws NoSuchElementException if empty
  2. 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
  3. orElseGet( Supplier<? extends T> other) : public method which returns the value if present else returns the return value of other. other is functional interface
  4. 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

  1. ifPresent( Consumer<? super T> consumer): public method used to perform some operation if data is present
  2. 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
  3. 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:

  1. equals(Object obj):  Compares 2 Optional objects, returns true if they are equal else returns false.
  2. hashCode():Returns the hash code value of the value if present or 0 (zero) if no value is present.
  3. 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 instanceCheck valueFetch valueOperational 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)

2 comments

    1. 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!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.