Sobes.tech
Junior — Middle

Can you list and explain different ways to use the Optional class in Java?

sobes.tech AI

Answer from AI

The Optional class in Java is used to wrap values that may be absent (null), to avoid NullPointerException and make code more readable and safe.

Main ways to use Optional:

  • Creating Optional:

    • Optional.of(value) — creates an Optional with a non-null value (throws if null).
    • Optional.ofNullable(value) — creates an Optional that can contain null.
    • Optional.empty() — creates an empty Optional.
  • Checking presence:

    • isPresent() — returns true if value is present.
    • ifPresent(Consumer) — executes a block if value is present.
  • Getting value:

    • get() — returns the value if present, throws if not.
    • orElse(defaultValue) — returns value or default if empty.
    • orElseGet(Supplier) — lazily returns default.
    • orElseThrow() — throws exception if no value.
  • Transforming and filtering:

    • map(Function) — applies a function if value exists.
    • flatMap(Function) — similar to map, but function returns Optional.
    • filter(Predicate) — returns Optional if value satisfies predicate.

Example:

Optional<String> optionalName = Optional.ofNullable(getName());
optionalName.ifPresent(name -> System.out.println("Name: " + name));

String defaultName = optionalName.orElse("Unknown");

int length = optionalName.map(String::length).orElse(0);
Can you list and explain different ways to use the… - sobes.tech