Middle
What do you know about the Optional class?
sobes.tech AI
Answer from AI
Optional<T> is a container class that can hold either a non-empty value of type T or be empty. It was added in Java 8 to solve the null pointer problem.
Main methods:
of(T value): Creates anOptionalwith a non-empty value. ThrowsNullPointerExceptionif the value isnull.ofNullable(T value): Creates anOptionalwith a non-empty value if present, or an emptyOptionalif the value isnull.empty(): Creates an emptyOptional.isPresent(): Returnstrueif a value is present, otherwisefalse.isEmpty(): Returnstrueif no value is present, otherwisefalse(added in Java 11).get(): Returns the value if present, otherwise throwsNoSuchElementException.orElse(T other): Returns the value if present, otherwise returnsother.orElseGet(Supplier<? extends T> other): Returns the value if present, otherwise returns the result ofSupplier. Preferable toorElse(T other)whenotheris costly to initialize.orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if present, otherwise throws an exception provided byexceptionSupplier.
Example usage to avoid NullPointerException:
// Instead of
User user = findUserById(userId);
if (user != null) {
String email = user.getEmail();
// ...
}
// You can use Optional
Optional<User> userOptional = findUserByIdOptional(userId);
userOptional.ifPresent(user -> {
String email = user.getEmail();
// ...
});
Comparison of orElse and orElseGet:
// Both calls will return DefaultUser if optionalUser is empty
// But in the case of orElse, new DefaultUser() will be called always,
// even if optionalUser contains a value
User user1 = optionalUser.orElse(new DefaultUser());
// In the case of orElseGet, new DefaultUser() will be called only
// if optionalUser is empty
User user2 = optionalUser.orElseGet(() -> new DefaultUser());
Optional helps make code more readable and safe by explicitly indicating that a value may be absent. It should not be used for class fields or method parameters if the missing value is an exceptional situation.