Junior — Middle
What functionality is implemented by the flatMap method in the Optional class?
sobes.tech AI
Answer from AI
The flatMap method in the Optional class in Java allows you to apply a function that returns another Optional to the value inside the original Optional, and "unwrap" the nested Optional into a single level.
If you have an Optional<T> and a function T -> Optional<U>, then flatMap will apply this function and return an Optional<U>, avoiding nested Optional<Optional<U>>.
Example:
Optional<String> optional = Optional.of("123");
Optional<Integer> result = optional.flatMap(s -> {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
});
System.out.println(result); // Optional[123]
If map were used instead, the result would be Optional<Optional<Integer>>, which is inconvenient for further processing.