Java SE API
Optional.ifPresent()
Execute a consumer only for presence. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
void ifPresent(Consumer<? super T> action)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| action | Consumer<? super T> | Present-value action |
Working Example
Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> stock = Map.of("A", 3); Optional.ofNullable(stock.get("A")).ifPresent(n -> System.out.println("Stock: " + n)); for (String id : List.of("A", "B")) { Optional.ofNullable(stock.get(id)).ifPresentOrElse(n -> System.out.println(id + ":" + n), () -> System.out.println(id + ":missing")); } }}