Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
JerryWang
Advisor
Advisor

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.

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.

Example 2

Instead of writing code like:


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

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

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:

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.

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:

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> ).