Optional Class in Java 8

Optional Class in Java 8:

Introduced a new Optional class in java 8 ( java.util package). this class is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. By using this we can avoids any runtime NullPointerExceptions which help us to write neat and clean java APIs and applications. Like Collections and arrays, it is also a Container to hold at most one value. Let us explore this new construct with some useful examples.

Advantages of Optional class in Java 8 :

  1. Null checks are not required.
  2. No more NullPointerException at run-time.
  3. We can develop clean and neat APIs.
  4. No more Boiler plate code

1.Basic Example of Optional class:

Optional.ofNullable() method returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional.

Optionaal.empty() method is useful to create an empty Optional object.

2.Example of Optional.map and flatmap:

3.Example of Optional.filter:


4.Example of Optional isPresent and ifPresent:

Optional.isPresent() returns true if the given Optional object is non-empty. Otherwise it returns false.

Optional.ifPresent() performs given action if the given Optional object is non-empty. Otherwise it returns false.


5.Example of Optional orElse:

It returns the value if present in Optional Container. Otherwise returns given default value.