Java SE API
Optional.ifPresentOrElse()
Select one action; since Java 9. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| action | Consumer<? super T> | Present action |
| emptyAction | Runnable | Absent 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")); } }}