Java Optional flatMap() Method
Example
Use a method that returns an Optional on the value:
import java.util.Optional;
public class Main {
static Optional<String> findCapital(String country) {
if (country.equals("Norway")) {
return Optional.of("Oslo");
}
return Optional.empty();
}
public static void main(String[] args) {
Optional<String> country = Optional.of("Norway");
Optional<String> capital = country.flatMap(c -> findCapital(c));
System.out.println(capital.orElse("Not found"));
}
}
Definition and Usage
The flatMap() method works like map(), but the lambda expression (a short block of code that works like a method) returns an Optional. Use it when you call a method that already returns an Optional.
With map(), you would get an Optional inside another Optional (Optional<Optional<String>>). flatMap() returns the inner Optional directly. If the first Optional is empty, the result is empty.
Syntax
public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
T refers to the data type of the value in the Optional. U refers to the data type of the value in the new Optional.
Parameter Values
| Parameter | Description |
|---|---|
| mapper | Required. A Function object or lambda expression that takes the value and returns an Optional. |
Technical Details
| Returns: | The Optional that mapper returns, or an empty Optional if there is no value. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods