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
Syntax
optional.ifPresent(action)
Parameters
| Parameter | Description |
|---|---|
actionConsumer<T> |
Code to run with the value. |
Return value
Nothing (void).
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
optional.map()· Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks.optional.orElse()· Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.- Java Optional · tutorial