Java Optional Cheat Sheet

Category: Creation

Methods / Descriptions:

> Optional.empty() - Creates an empty Optional

> Optional.of(value) - Creates Optional with non-null value(throws if null)

> Optional.ofNullalbe(value) - Creates Optional that may hold null

Example:

> Optional<String> o = Optional.empty();

> Optional.of("Hi")

> Optional.ofNullalbe(null)

Category: Check Presence

Methods / Descriptions:

> isPresent() - Return true if value exist

> isEmpty() - Return true if no value

> Optional.ofNullalbe(value) - Creates Optional that may hold null

Example:

> opt.isPresent()

> opt.isEmpty()

Category: Conditional Execution

Methods / Descriptions:

> ifPresent(Consumer) - Runs code if value exists

> ifPresentOrElse(Consumer, Runnable) - Runs one action if present, another if empty

Example:

> opt.ifPresent(System.out::println)

> opt.ifPresentOrElse(System.out::println, () System.out.println("Empty"))

Category: Get Value

Methods / Descriptions:

> get() - Returns value (throws if empty) β€” avoid unless sure

> orElse(default) - Returns value or default

> orElseGet(Supplier) - Returns value or generates default

> orElseThrow() - Throws NoSuchElementException if empty

> orElseThrow(Supplier) - Throws custom exception if empty

Example:

> opt.get()

> opt.orElse("Default")

> opt.orElseGet(() -> "Generated")

> opt.orElseThrow()

> opt.orElseThrow(() -> new IllegalArgumentException())

Category: Transform

Methods / Descriptions:

> map(Function) - Transforms value if present

> flatMap(Function) - Like map but avoids nested Optionals

Example:

> opt.map(String::length)

> opt.flatMap(v -> Optional.of(v.toUpperCase()))

Category: Filter

Methods / Descriptions:

> filter(Predicate) - Keeps value if matches condition

Example:

> opt.filter(v -> v.startsWith("A"))

Category: Stream API

Methods / Descriptions:

> stream() - Converts Optional to Stream

Example:

> opt.stream().forEach(System.out::println)



Ex. All in One

import java.util.Optional;

public class OptionalCheatSheetDemo {
  public static void main(String[] args) {
    Optional<String> opt = Optional.ofNullable("Hello");

    // Check presence
    if (opt.isPresent()) {
      System.out.println("Value: " + opt.get());
    }

    // Conditional execution
    opt.ifPresentOrElse(
      val -> System.out.println("Upper: " + val.toUpperCase()),
      () -> System.out.println("No value")
    );

    // Transform
    int length = opt.map(String::length).orElse(0);
    System.out.println("Length: " + length);

    // Filter
    opt.filter(v -> v.startsWith("H"))
      .ifPresent(v -> System.out.println("Starts with H: " + v));

    // Safe default
    String result = opt.orElseGet(() -> "Default Value");
    System.out.println("Result: " + result);
  }
}

Additional examples

Optional<String> opt = Optional.ofNullable("HELLO");
     
    if (opt.isPresent()) {
      System.out.println("Value: " + opt.get());
    }
     
    opt.ifPresentOrElse(
      val -> System.out.println("Its not null"),
      () -> System.out.println("It is null")
    );

Output

Value: HELLO
Its not null


βœ… Pro Tip:

  • Use map + filter to chain transformations without null checks.
  • Use orElseGet instead of orElse when the default value is expensive to compute.
  • Avoid using Optional for class fields or method parameters β€” it’s meant for return types.
← Back to Learning Journey