What is the Optional.ifPresent method in Java?
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.
What is the 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)
Argument
This method takes the function to be executed as an argument. The function will be executed only if the Optional object contains a value.
Return value
This method does not return any value.
Code
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);});}}
Explanation
In the above code:
- In line 1, we import the
Optionalclass.
import java.util.Optional;
- In line 5, we create an
Optionalobject of theIntegertype with value1, using theofmethod.
Optional<Integer> optional1 = Optional.of(1);
- In line 6, we call the
ifPresentmethod on theoptional1object with a function as an argument. This function is executed and prints the value of theoptional1object.
optional1.ifPresent((value)->{
System.out.println("Value at Optional1 is : " + value);
});
// Optional1 is. : 1
- In line 10, we use the
emptymethod to get an emptyOptionalobject of theIntegertype. The returned object does not have any value.
Optional<Integer> optional2 = Optional.empty();
- In line number 11, we call the
ifPresentmethod on theoptional2object with a function as an argument. This function does not get executed because theoptional2object 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