Skip to Content
Author's profile photo Jerry Wang

Using Optional in Java 8

Optional class is available in Java8. Let’s use some examples to understand its logic.

Example 1

Optional instance acts as a wrapper for your productive Java class. For example I have a Person class:


class Person {
  private String mName;
  public Person(String name) {
   mName = name;
  }
  public void greet() {
   System.out.println("I am: " + mName);
  }
}

line 21 will trigger an null pointer exception.

/wp-content/uploads/2015/12/clipboard1_851396.png

Console will print out “Error: java.lang.NullPointerException – null”. To avoid it we can use method ofNullable and evaluate the availability using method isPresent. The following two lines 28 and 32 will print false and true accordingly.

/wp-content/uploads/2015/12/clipboard2_851397.png

Example 2

Instead of writing code like:


if ( person != null ) {
     person.greet();
}

to avoid null pointer exception before Java 8, now we can write:

/wp-content/uploads/2015/12/clipboard3_851398.png

The lambda expression specified within method ifPresent will only be executed if the method isPresent() returns true.

Example 3

Now we can avoid the ( condition ) ? x: y statement using orElse method of Optional:

/wp-content/uploads/2015/12/clipboard4_851399.png

/wp-content/uploads/2015/12/clipboard5_851400.png

Example 4

We need to figure out if a person is Jerry or not. The old style has to always check whether the reference jerry is available or not.

/wp-content/uploads/2015/12/clipboard6_851401.png

The new approach is to use filter method of instance of class Optional<Person>, thus the null check could be avoided (replaced by ifPresent ).


old style-> Jerry found: Jerry
new style-> Jerry found: Jerry

The enhanced version using map function:

/wp-content/uploads/2015/12/clipboard7_851402.png

Difference between method map and flatMap

map accepts a function returning the unwrapped data without Optional ( type U ), and the flatMap accepts a function returning the wrapped data with Optional ( type Optional<U> ).

/wp-content/uploads/2015/12/clipboard8_851403.png

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.