The ifPresentOrElse
method of the Optional
class is an instance method that is used to perform an action based on whether or not the object’s value is present.
This method implements the Consumer
interface and an implementation of the Runnable
interface.
The accept
method of the Consumer
interface will be called when the value is present.
The value of the optional instance is passed as the parameter for the accept
method.
The run
method of the Runnable
interface will be called with no parameters when the value is not present.
To learn what
Optional
class is, refer to What is the optional class in Java?
Optional
classThe Optional
class is defined in the java.util
package. Use the import statement below to import the Optional
class.
import java.util.Optional;
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
Consumer<? super T> action
: An implementation of the Consumer
interface.
Runnable emptyAction
: An implementation of the Runnable
interface.
The ifPresentOrElse
method doesn’t return anything.
In the code below, we create an instance of the Optional
class using the method ofNullable
for different values.
The implementation of the Consumer
interface that prints the value stored in the Optional
instance and the implementation of the Runnable
interface that prints the string, No value in optional object
is defined.
Refer to What is the optional class in Java? to learn more about the
ofNullable
method.
In the first example, we create an Optional
object from a non-empty string.
Hence, the accept()
method of the Consumer
interface implementation gets executed as the optional object has a value.
In the third example, we create an Optional
object from a null
value. Since the value passed is null
, the method ofNullable
replaces it with an empty Optional
.
Hence, the run()
method of the Runnable
interface implementation is executed as the optional object has no value.
import java.util.Optional;import java.util.function.Consumer;class Main {public static void main(String[] args) {Consumer<String> stringConsumer = (s) -> System.out.println("The value stored in Optional object - " + s);Runnable runnable = () -> System.out.println("No value stored in the Optional object");String test = "hello-educative";Optional<String> stringOptional = Optional.ofNullable(test);System.out.println("When a value is present - ");stringOptional.ifPresentOrElse(stringConsumer, runnable);System.out.println("----------");test = null;System.out.println("When no value is present - ");stringOptional = Optional.ofNullable(test);stringOptional.ifPresentOrElse(stringConsumer, runnable);}}
When a value is present -
The value stored in Optional object - hello-educative
----------
When no value is present -
No value stored in the Optional object