Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.flatMap: practical reference

Optional.flatMap: practical reference: Optional.flatMap(mapper) returns the Optional produced by the mapper without another wrapper for a present value, and returns empty for an empty receiver.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Optional.flatMap(...)

Optional.flatMap(mapper) returns the Optional produced by the mapper without another wrapper for a present value, and returns empty for an empty receiver.

Use flatMap when a lookup or validation function already returns Optional, avoiding Optional<Optional> nesting.

The mapper is not invoked for an empty receiver and its exceptions propagate; do not use it for an effect that must always occur.

A null mapper or null mapper result causes NullPointerException; Optional.empty() returned by the mapper is a valid result.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var value = java.util.Optional.of("21").flatMap(text -> java.util.Optional.of(Integer.parseInt(text)));
        System.out.println(value.orElse(0) * 2);
    }
}

Result

42

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources