Java Optional<T> class in the java.util package tries to deal with NullPointerException gracefully.
Methods that may return nothing should return an Optional instead of null.
An Optional is a wrapper for a non-null value that may or may not contain a non-null value.
Its isPresent() method returns true if it contains a non-null value, false otherwise.
Its get() method returns the non-null value if it contains a non-null value, and throws a NoSuchElementException otherwise.
Optional<T> class provides three static factory methods to create its objects.
Method | Description |
---|---|
<T> Optional<T> empty() | returns an empty Optional. That is, the Optional<T> returned from this method does not contain a non-null value. |
<T> Optional<T> of(T value) | Returns an Optional containing the specified value as the non-null value. If the specified value is null, it throws a NullPointerException. |
<T> Optional<T> ofNullable(T value) | Returns an Optional containing the specified value if the value is non-null. If the specified value is null, it returns an empty Optional. |
The following code shows how to create Optional objects:
// Create an empty Optional Optional<String> empty = Optional.empty(); // Create an Optional for the string "Hello" Optional<String> str = Optional.of("Hello"); // Create an Optional with a String that may be null String nullableString = ""; // get a string that may be null... Optional<String> str2 = Optional.of(nullableString);
The following code prints the value in an Optional if it contains a non-null value:
// Create an Optional for the string "Hello" Optional<String> str = Optional.of("Hello"); // Print the value in Optional if (str.isPresent()) { String value = str.get(); System.out.println("Optional contains " + value); } else { System.out.println("Optional is empty."); }
You can use the ifPresent(Consumer<? super T> action) method to take an action on the value contained in the Optional.
If the Optional is empty, this method does not do anything.
// Create an Optional for the string "Hello" Optional<String> str = Optional.of("Hello"); // Print the value in the Optional, if present str.ifPresent(value -> System.out.println("Optional contains " + value));
The Optional<T> class describes a non-null reference type value or its absence.
java.util package contains three more classes named OptionalInt, OptionalLong, and OptionalDouble to deal with optional primitive values.
The following code shows how to use the OptionalInt class:
// Create an empty OptionalInt OptionalInt empty = OptionalInt.empty(); // Use an OptionaInt to store 1 OptionalInt number = OptionalInt.of(1); if(number.isPresent()){ int value = number.getAsInt(); System.out.println("Number is " + value); } else { System.out.println("Number is absent."); }