Java 25 (LTS) reference · Optional

Java Optional ifPresent() Method

Run an action with the value only if it's present. ifPresentOrElse() also handles the empty case.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

optional.ifPresent(action)

Parameters

ParameterDescription
action
Consumer<T>
Code to run with the value.

Return value

Nothing (void).

Examples

Act only when present
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Optional.of("[email protected]").ifPresent(e -> System.out.println("sending to " + e));
        Optional.empty().ifPresent(e -> System.out.println("never printed"));
    }
}

Output

sending to [email protected]

Run this on your computer — see “Get Started” for setup.

Handle both cases
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Optional<String> coupon = Optional.empty();
        coupon.ifPresentOrElse(c -> System.out.println("applied " + c), () -> System.out.println("no coupon"));
    }
}

Output

no coupon

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?