‘java.util.Optional’ is a class introduced in Java 8 to represent an optional (nullable) value. It’s designed to help you avoid dealing with ‘null’ references and to make your code more robust and expressive when working with potentially absent values.
Optional optionalValue = Optional.of
("This is a non-null value");
Optional emptyOptional = Optional.empty();
The Optional.of() method is used when you are sure that the value is not null. If you are uncertain about the value, you can use Optional.ofNullable():
String potentiallyNullValue = ...
Optional optionalValue =
Optional.ofNullable(potentiallyNullValue);
Optional optionalValue = ...
String value = optionalValue.get();
String defaultValue =
optionalValue.orElse("Default Value");
Optional optionalValue = ...
if (optionalValue.isPresent()) {
// Value is present
String value = optionalValue.get();
}
Optional optionalValue = ...
optionalValue.ifPresent
(val -> System.out.println("Value is present: " + val));
Optional optionalValue = ...
String result = optionalValue.map
(val -> val.toUpperCase())
.filter(val -> val.startsWith("A"))
.orElse("Default");
List values = ...
Optional first =
values.stream().filter(val ->
val.startsWith("A")).findFirst();
The Optional class encourages better practices by making it explicit that a value can be absent, reducing the chances of NullPointerExceptions and leading to more readable and safer code. However, it’s important to use Optional judiciously, as overuse can lead to excessive verbosity. It’s typically most valuable when working with methods that return optional values, representing uncertainty about the presence of a result.