map and flatMap
- Java course
- Advanced
- Lesson 9/82
- 5 min
Learn map and flatMap on Optional.
Transforming with Optional map
Optional.map(function) applies the function to the value when it is present and returns the result wrapped in a new Optional. When the value is absent it returns an empty Optional; the function is never called.
Example: opt.map(String::length). If opt is Optional.of("Alex") the result is Optional.of(4). For an empty Optional the result stays empty. This is the shortest way to transform safely without explicit null checks.
Nested Optional: flatMap
If the function you pass to map already returns an Optional, the result becomes Optional<Optional<T>>; this is awkward. flatMap flattens this nested structure.
Example: opt.flatMap(this::lookup). Here lookup returns Optional<String>. With map you would get Optional<Optional<String>>; flatMap gives a single Optional<String>. This is ideal when a second lookup may fail too.
Practice Find string length with map
Create an Optional<String> with Optional.of("Alex"). Use map(String::length) to get the length as an Optional<Integer>. Fall back to 0 with orElse(0). Print the result with System.out.println.
Starter code
import java.util.Optional;
// Wrap "Alex" with Optional.of
// Map to length, fall back to 0 with orElse
// Print the resultSample solution
import java.util.Optional;
public class MapOptional {
public static void main(String[] args) {
Optional<String> name = Optional.of("Alex");
int length = name.map(String::length).orElse(0);
System.out.println(length);
}
}Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Optional.map(String::length) return?
- Optional<Integer> Correct answer
- void
- Integer
- Stream<Integer>
Explanation: map returns the result wrapped in another Optional.
2 Complete the map call
Optional<Integer> len = opt.____(String::length);
Optional<Integer> len = opt.map(String::length);
Explanation: map applies a function and wraps the result.
3 Match the map vs flatMap difference
| Term | Meaning |
|---|---|
map |
Returns Optional<R> |
flatMap |
Flattens nesting |
Function<T,R> |
map's function |
Function<T,Optional<R>> |
flatMap's function |