What is the OptionalDouble.ifPresent method in Java?
The ifPresent method executes the given DoubleConsumer function if the value is present in the OptionalDouble object.
In Java, the
OptionalDoubleobject is a container object that may or may not contain adoublevalue. TheOptionalDoubleclass is present in thejava.utilpackage.
Syntax
public void ifPresent(DoubleConsumer consumer)
Parameters
This method takes the DoubleConsumer function to be executed as a parameter. The function will only be executed if the OptionalDouble 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.OptionalDouble;class OptionalDoubleIfPresentExample {public static void main(String[] args) {OptionalDouble optional1 = OptionalDouble.of(1.5);optional1.ifPresent((doubleValue)->{System.out.println("Double Value at Optional1 is : " + doubleValue);});OptionalDouble optional2 = OptionalDouble.empty();optional2.ifPresent((doubleValue)->{System.out.println("Double Value at Optional2 is : " + doubleValue);});}}
Explanation
In the code above:
- In line 1, we import the
OptionalDoubleclass.
import java.util.OptionalDouble;
- In line 5, we use the
ofmethod to create anOptionalDoubleobject with the value1.
OptionalDouble optional1 = OptionalDouble.of(1.5);
- In line 6, we call the
ifPresentmethod on theoptional1object with aDoubleConsumerfunction as an argument. This function will be executed and print the value of theoptional1object.
optional1.ifPresent((doubleValue)->{
System.out.println("Double Value at Optional1 is : " + doubleValue);
});
// Optional1 is. : 1.5
- In line 10, we use the
emptymethod to get an emptyOptionalDoubleobject. The returned object doesn’t have any value.
OptionalDouble optional2 = OptionalDouble.empty();
- In line 11, we call the
ifPresentmethod on theoptional2object with aDoubleConsumerfunction as an argument. This function will not get executed because theoptional2object doesn’t have any value.
optional2.ifPresent((doubleValue)->{
System.out.println("Double Value at Optional2 is : " + doubleValue);
});
// the function passed as an argument will not get executed