In Java, the Optional object is a container object which may or may not contain a value.
The Optional class is present in the java.util package. Using the Optional object’s isPresent method, we can replace the multiple null check.
Read more about the
Optionalclass here.
ifPresent method of the Optional class?The ifPresent method executes the given function if the value is present in the Optional object.
public void ifPresent(Consumer<? super T> action)
This method takes the function to be executed as an argument. The function will be executed only if the Optional object contains a value.
This method does not return any value.
The below code denotes how to use the ifPresent method.
import java.util.Optional;class OptionalIfPresentExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);optional1.ifPresent((value)->{System.out.println("Value at Optional1 is : " + value);});Optional<Integer> optional2 = Optional.empty();optional2.ifPresent((value)->{System.out.println("Value at Optional2 is : " + value);});}}
In the above code:
Optional class.import java.util.Optional;
Optional object of the Integer type with value 1, using the of method.Optional<Integer> optional1 = Optional.of(1);
ifPresent method on the optional1 object with a function as an argument. This function is executed and prints the value of the optional1 object.optional1.ifPresent((value)->{
System.out.println("Value at Optional1 is : " + value);
});
// Optional1 is. : 1
empty method to get an empty Optional object of the Integer type. The returned object does not have any value.Optional<Integer> optional2 = Optional.empty();
ifPresent method on the optional2 object with a function as an argument. This function does not get executed because the optional2 object does not have any value.optional2.ifPresent((value)->{
System.out.println("Value at Optional1 is : " + value);
});
// the function passed as an argument will not get executed