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
OptionalLongobject is a container object that may or may not contain alongvalue. TheOptionalLongclass is present in thejava.utilpackage.
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
OptionalLongobject 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
OptionalLongclass.
import java.util.OptionalLong;
- In line 5, we use the
ofmethod to create anOptionalLongobject with value1.
OptionalLong optional1 = OptionalLong.of(1);
- In line 6, we call the
ifPresentmethod on theoptional1object with aLongConsumerfunction as an argument. This function will be executed and print the value of theoptional1object.
optional1.ifPresent((longValue)->{
System.out.println("Long Value at Optional1 is : " + longValue);
});
// Optional1 is. : 1
- In line 10, we use the
emptymethod to get an emptyOptionalLongobject. The returned object doesn’t have any value.
OptionalLong optional2 = OptionalLong.empty();
- In line 11, we call the
ifPresentmethod on theoptional2object with aLongConsumerfunction as an argument. This function will not get executed because theoptional2object 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