In Java 8, the Optional
class is a container class that is used to represent the presence or absence of a value. It is used to avoid null
checks and to provide a more concise and readable way of dealing with nullable values.
To instantiate an Optional
object, you can use one of the following methods:
empty()
: creates an empty Optional
object.of(T value)
: creates an Optional
object that contains the specified value. If the value is null
, a NullPointerException
is thrown.ofNullable(T value)
: creates an Optional
object that contains the specified value, or an empty Optional
object if the value is null
.For example:
// empty Optional Optional<String> empty = Optional.empty(); // Optional containing a non-null value Optional<String> nonNull = Optional.of("Hello"); // Optional containing a null value Optional<String> nullable = Optional.ofNullable(null);
You can use the isPresent()
method to check if an Optional
object contains a value, and the get()
method to retrieve the value. For example:
Optional<String> opt = Optional.of("Hello"); if (opt.isPresent()) { String value = opt.get(); System.out.println(value); // prints "Hello" }
The Optional
class also provides methods for manipulating and transforming Optional
objects, such as map()
, flatMap()
, and filter()
.
For more information on the Optional
class in Java 8, you can refer to the Java documentation.