0Pricing
Java Academy · Lesson

Transforming Optionals: map and flatMap

Chain transformations with map and flatMap to process values without null checks.

Transforming Optionals: map and flatMap

map() transforms the value inside an Optional if present. flatMap() avoids nested Optionals when the transformation itself returns an Optional.

map: Transforming the Value

map(Function) applies the function to the value if present, wrapping the result in a new Optional. Returns empty if originally empty.

import java.util.Optional;

Optional<String> name = Optional.of("alice");

Optional<String> upper = name.map(String::toUpperCase);
System.out.println(upper.get()); // ALICE

Optional<Integer> length = name.map(String::length);
System.out.println(length.get()); // 5

// Empty in → empty out
Optional<String> empty = Optional.<String>empty().map(String::toUpperCase);
System.out.println(empty.isPresent()); // false

All lessons in this course

  1. Why Optional Exists
  2. Creating and Inspecting Optionals
  3. Transforming Optionals: map and flatMap
  4. Optional Best Practices
← Back to Java Academy