The ifPresentOrElse() method of the Optional class performs an action when a value is present and another action when the Optional is empty. It provides a convenient way to handle both cases without explicitly checking for the value.
- The method accepts a Consumer for handling a present value and a Runnable for handling an empty Optional.
- ifPresentOrElse() was introduced in Java 9.
- The method throws NullPointerException if the action is null when a value is present, or if the emptyAction is null when the Optional is empty.
Examples:
Input: Optional = Optional[9455]
Output: Value is present, its: 9455Input: Optional = Optional.empty
Output: Value is empty
Syntax:
public void ifPresentOrElse(
Consumer<? super T> action,
Runnable emptyAction
)
1. Using ifPresentOrElse() with a Present Value
The following program creates an Optional containing an integer value. The Consumer action executes because the value is present.
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<Integer> op = Optional.of(9455);
System.out.println("Optional: " + op);
op.ifPresentOrElse(
value -> {
System.out.println(
"Value is present, its: " + value);
},
() -> {
System.out.println("Value is empty");
}
);
}
}
Output
Optional: Optional[9455] Value is present, its: 9455
Explanation: The Optional contains 9455, so the Consumer action executes. The emptyAction is not executed because a value is present.
2. Using ifPresentOrElse() with an Empty Optional
The following program creates an empty Optional. The Runnable action executes because no value is present.
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<Integer> op = Optional.empty();
System.out.println("Optional: " + op);
op.ifPresentOrElse(
value -> {
System.out.println(
"Value is present, its: " + value);
},
() -> {
System.out.println("Value is empty");
}
);
}
}
Output
Optional: Optional.empty Value is empty
Explanation: The Optional is empty, so the Runnable action executes and prints "Value is empty". The Consumer action is not executed because no value is present.
Note: NullPointerException is thrown when the required action is null.