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 OptionalInt class is present in the java.util package.

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 OptionalInt class.

  • In line 5, we created an OptionalInt object with value 1 using the of method.

  • In line 6, we called the ifPresent method on the optional1 object with an IntConsumer function as an argument. This function will get executed and print the value of the optional1 object.

  • In line 10, we used the empty method to get an empty OptionalInt object. The returned object doesn’t have any value.

  • In line 11, we called the ifPresent method on the optional2 object with a IntConsumer function as an argument. This function will not get executed because the optional2 object doesn’t have a value.

Free Resources