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()); // falseAll lessons in this course
- Why Optional Exists
- Creating and Inspecting Optionals
- Transforming Optionals: map and flatMap
- Optional Best Practices