Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.map: practical reference

Optional.map: practical reference: Optional.map(mapper) applies the Function to a present value and wraps a non-null result, while a null result or empty receiver yields Optional.empty().

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

Syntax

Optional.map(...)

Optional.map(mapper) applies the Function to a present value and wraps a non-null result, while a null result or empty receiver yields Optional.empty().

Use map for a pure transformation of an optional value when the function returns a plain result rather than another Optional.

The mapper does not run for an empty receiver; the original Optional remains immutable, and a function exception propagates to the caller.

A null mapper causes NullPointerException; null returned by the mapper is not an error but is converted to empty through ofNullable semantics.

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 length = java.util.Optional.of("Java").map(String::length);
        System.out.println(length.orElse(0));
    }
}

Result

4

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

Sources