Sobes.tech
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 an Optional with a non-empty value. Throws NullPointerException if the value is null.
  • ofNullable(T value): Creates an Optional with a non-empty value if present, or an empty Optional if the value is null.
  • empty(): Creates an empty Optional.
  • isPresent(): Returns true if a value is present, otherwise false.
  • isEmpty(): Returns true if no value is present, otherwise false (added in Java 11).
  • get(): Returns the value if present, otherwise throws NoSuchElementException.
  • orElse(T other): Returns the value if present, otherwise returns other.
  • orElseGet(Supplier<? extends T> other): Returns the value if present, otherwise returns the result of Supplier. Preferable to orElse(T other) when other is costly to initialize.
  • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if present, otherwise throws an exception provided by exceptionSupplier.

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.