An overview of the

The famous NullPointerException is by far the most common cause of Java application failure. In the past, To address null pointer exceptions, Google’s famous Guava project introduced the Optional class. Guava encourages programmers to write cleaner code by checking for null values to prevent code contamination. Inspired by Google Guava, the Optional class has become part of the Java 8 class library.

Optional is defined as a simple container whose value may or may not be NULL. Before Java 8, a function was supposed to return a non-empty object but occasionally returned NULL. After Java 8, it is not recommended that you return NULL but Optional.

methods

The Optional class has the following methods:

  • Empty (): Returns an empty Optional instance.
  • Equals (Object obj): Checks whether other objects are equal to Optional.
  • Filter (function): Returns an Optional description of the value if it exists and the method returns true, otherwise returns an empty Optional.
  • FlatMap (function): Returns the function-processed Optional class if the value exists, otherwise returns an empty Optional class
  • Get (): Returns the value if included in this Optional, otherwise throws an exception: NoSuchElementException
  • HashCode (): returns a hashCode for an existing value, or 0 if the value does not exist.
  • IfPresent (function): Call consumer with the value if it exists, otherwise do nothing.
  • IsPresent (): The method returns true if the value exists, false otherwise.
  • Map (function): If there is a value, call the mapping function on it to get the return value. If the return value is not null, create an Optional containing the map return value as the map method return value, otherwise return empty Optional.
  • Static of(value): Returns an Optional value that specifies a non-null value.
  • Static ofNullable(value): Returns the specified value described in Optional if it is not null, otherwise returns empty Optional.
  • OrElse (other): Returns the value if it exists, otherwise returns other.
  • OrElseGet (function): Returns the value if it exists, otherwise fires the method and returns the result of the method call.
  • OrElseThrow (function): Returns the contained value if it exists, otherwise throws the exception specified by the method
  • ToString (): Returns an Optional non-empty string

All of these methods can use lambda expressions