Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.ifPresent: practical reference

Optional.ifPresent: practical reference: Optional.ifPresent(action) invokes the Consumer exactly once with the present value and performs no action for an empty Optional.

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

Syntax

Optional.ifPresent(...)

Optional.ifPresent(action) invokes the Consumer exactly once with the present value and performs no action for an empty Optional.

Use it for a conditional side effect, such as recording a found value, when the absence path intentionally needs no handling.

The method returns void and is not a transformation; an exception thrown by the Consumer propagates to the caller.

A null action causes NullPointerException only when a value is present; for an empty Optional the unused action is not invoked.

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 {
        java.util.Optional.of("Java").ifPresent(text -> System.out.println(text.length()));
    }
}

Result

4

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

Sources