What is the OptionalInt.ifPresent method in Java?
In Java, the OptionalInt object is a container object that may or may not contain an integer value.
The
OptionalIntclass is present in thejava.utilpackage.
The ifPresent method will execute the given IntConsumer function if the value is present in the OptionalInt object.
Syntax
public void ifPresent(IntConsumer consumer)
Argument
This method takes the IntConsumer function to be executed as an argument. The function will be executed only if the OptionalInt object contains a value.
Return value
This method doesn’t return a value.
Code
The code below denotes how to use the ifPresent method.
import java.util.OptionalInt;class OptionalIntIfPresentExample {public static void main(String[] args) {OptionalInt optional1 = OptionalInt.of(1);optional1.ifPresent((intValue)->{System.out.println("Int Value at Optional1 is : " + intValue);});OptionalInt optional2 = OptionalInt.empty();optional2.ifPresent((intValue)->{System.out.println("Int Value at Optional2 is : " + intValue);});}}
Explanation
In the code above:
-
In line 1, we imported the
OptionalIntclass. -
In line 5, we created an
OptionalIntobject with value1using theofmethod. -
In line 6, we called the
ifPresentmethod on theoptional1object with anIntConsumerfunction as an argument. This function will get executed and print the value of theoptional1object. -
In line 10, we used the
emptymethod to get an emptyOptionalIntobject. The returned object doesn’t have any value. -
In line 11, we called the
ifPresentmethod on theoptional2object with aIntConsumerfunction as an argument. This function will not get executed because theoptional2object doesn’t have a value.