The ifPresent
method of the Optional
class is an instance method that performs an action if the class instance contains a value.
This method takes in the Consumer
interface’s implementation whose accept
method will be called with the value of the optional instance as the parameter to the accept
method.
To learn about the
Optional
class, refer to this shot.
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 ifPresent(Consumer<? super T> action)
Consumer<? super T> action
: An implementation of the Consumer
interface.The method doesn’t return anything.
We create an instance of the Optional
class in the code below using the ofNullable
method. We create this class for different values and for the Consumer
interface’s implementation that prints the value stored in the Optional
instance.
To learn more about the
ofNullable
method, refer to What is the optional class in Java?.
In the first example, we create an Optional
object from a non-empty string. Hence, the Consumer
interface implementation gets executed and prints the value stored in the Optional
object.
In the second example, we create an Optional
object from a null
value. As the value passed is null
, the ofNullable
method replaces it with an empty Optional
.
Hence, the Consumer
interface implementation is not 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);String test = "hello-educative";Optional<String> stringOptional = Optional.ofNullable(test);System.out.println("When a value is present - ");stringOptional.ifPresent(stringConsumer);System.out.println("----------");test = null;System.out.println("When no value is present - ");stringOptional = Optional.ofNullable(test);stringOptional.ifPresent(stringConsumer);}}