Skip to content

Java Optional – Quick Reference Sheet

1. Creating Optionals

MethodExampleNotes
Optional.empty()Optional<String> opt = Optional.empty();Empty Optional
Optional.of(value)Optional<String> opt = Optional.of("Java");Throws NPE if value is null
Optional.ofNullable(value)Optional<String> opt = Optional.ofNullable(null);Safe for nullable values

2. Checking Presence

java
opt.isPresent();              // true/false
opt.ifPresent(v -> System.out.println(v));
  • isPresent() → check if value exists
  • ifPresent(Consumer) → run lambda if value exists

3. Retrieving Values

MethodExampleNotes
get()opt.get();Use only if sure value exists
orElse(T)opt.orElse("Default");Default if empty
orElseGet(Supplier)opt.orElseGet(() -> "Lazy Default");Lazy default computation
orElseThrow(Supplier)opt.orElseThrow(() -> new RuntimeException());Throw if empty

4. Transforming Values

java
opt.map(String::toUpperCase);       // transform value
opt.flatMap(v -> Optional.of(v.trim())); // flatten nested Optionals
  • map() → transform value
  • flatMap() → transform and flatten nested Optional

5. Filtering Values

java
opt.filter(v -> v.startsWith("J"));
  • Returns empty Optional if predicate fails

6. Working with Streams

java
list.stream()
    .filter(s -> s.startsWith("b"))
    .findFirst(); // returns Optional
  • Use Optionals with findFirst(), findAny()

7. Chaining Optionals

java
String result = Optional.ofNullable("  java  ")
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(String::toUpperCase)
                        .orElse("DEFAULT");
  • Combine map, filter, flatMap, orElse for safe chaining

8. Avoiding Null Checks Example

java
String city = Optional.ofNullable(person)
                      .map(Person::getAddress)
                      .map(Address::getCity)
                      .orElse("Unknown");
  • Avoids nested null checks gracefully

9. Common Methods Summary

MethodPurpose
empty()Create empty Optional
of(T)Create Optional with value
ofNullable(T)Create Optional, null-safe
isPresent()Check presence
ifPresent(Consumer)Run code if value exists
get()Retrieve value (unsafe if empty)
orElse(T)Default if empty
orElseGet(Supplier)Lazy default if empty
orElseThrow(Supplier)Throw exception if empty
map(Function)Transform value
flatMap(Function)Transform and flatten Optional
filter(Predicate)Keep value if predicate true

Best Practices

  • Use Optional for return types, not fields
  • Avoid get() without checking presence
  • Chain transformations for clean, null-safe code

© 2023-2025 Maduranga Kannangara. Feel free to use or share this content. Attribution is appreciated but not required.