Optional

Description

Java 8 has introduced an java.util.Optional<T> class to deal with NullPointerException gracefully.

An Optional is a wrapper for a non-null value that may or may not contain a non-null value.

Methods that may return null should return an Optional instead of null.

The isPresent() from Optional<T> returns true if it contains a non-null value, false otherwise.

get() method returns the non-null value if it contains a non-null value, and throws a NoSuchElementException otherwise.

When a method returns an Optional, you must check if it contains a non-null value before asking it for the value.

If get() method is called before making sure it contains a non-null value, a NoSuchElementException is thrown out instead of a NullPointerException.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial