Optional
is a class introduced in Java 8 to deal with the problem of null references. It is part of the java.util
package and is designed to provide a more robust way of handling situations where a value may or may not be present.
Optional.empty()
: Creates an empty Optional
.Optional.of(value)
: Creates an Optional
with a non-null value.Optional.ofNullable(value)
: Creates an Optional
with a value, which can be null.Optional<String> emptyOptional = Optional.empty();
Optional<String> nonNullOptional = Optional.of("Hello");
Optional<String> nullableOptional = Optional.ofNullable(null);
Accessing the Value:
get()
: Retrieves the value if present, or throws NoSuchElementException
if not.orElse(defaultValue)
: Retrieves the value if present, or returns a default value if not.orElseGet(supplier)
: Retrieves the value if present, or gets a value from the provided Supplier
if not.orElseThrow(exceptionSupplier)
: Retrieves the value if present, or throws an exception provided by the supplier if not.String value = nonNullOptional.get();
String orElseValue = emptyOptional.orElse("Default");
String orElseGetValue = emptyOptional.orElseGet(() -> "Default from supplier");
String orElseThrow = emptyOptional.orElseThrow(() -> new RuntimeException("No value present"));