What is the OptionalLong.ifPresent method in Java?

The ifPresent method executes the given LongConsumer function if the value is present in the OptionalLong object.

In Java, the OptionalLong object is a container object that may or may not contain a long value. The OptionalLong class is present in the java.util package.

Syntax

public void ifPresent(LongConsumer consumer)

Parameters

This method takes the LongConsumer function to be executed as an argument.

The function will only be executed if the OptionalLong object contains a value.

Return value

The ifPresent method doesn’t return any value.

Code

The code below denotes how to use the ifPresent method.

import java.util.OptionalLong;
class OptionalLongIfPresentExample {
public static void main(String[] args) {
OptionalLong optional1 = OptionalLong.of(1);
optional1.ifPresent((longValue)->{
System.out.println("Long Value at Optional1 is : " + longValue);
});
OptionalLong optional2 = OptionalLong.empty();
optional2.ifPresent((longValue)->{
System.out.println("Long Value at Optional2 is : " + longValue);
});
}
}

Explanation

In the code above:

  • In line 1, we import the OptionalLong class.
import java.util.OptionalLong;
  • In line 5, we use the of method to create an OptionalLong object with value 1.
OptionalLong optional1 = OptionalLong.of(1);
  • In line 6, we call the ifPresent method on the optional1 object with a LongConsumer function as an argument. This function will be executed and print the value of the optional1 object.
optional1.ifPresent((longValue)->{
    System.out.println("Long Value at Optional1 is : " + longValue);
});
// Optional1 is. : 1 
  • In line 10, we use the empty method to get an empty OptionalLong object. The returned object doesn’t have any value.
OptionalLong optional2 = OptionalLong.empty();
  • In line 11, we call the ifPresent method on the optional2 object with a LongConsumer function as an argument. This function will not get executed because the optional2 object doesn’t have any value.
optional2.ifPresent((longValue)->{
    System.out.println("Long Value at Optional1 is : " + longValue);
});
// the function passed as an argument will not get executed

Free Resources