The ifPresent
method executes the given DoubleConsumer
function if the value is present in the OptionalDouble
object.
In Java, the
OptionalDouble
object is a container object that may or may not contain adouble
value. TheOptionalDouble
class is present in thejava.util
package.
public void ifPresent(DoubleConsumer consumer)
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.
The ifPresent
method doesn’t return any value.
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);});}}
In the code above:
OptionalDouble
class.import java.util.OptionalDouble;
of
method to create an OptionalDouble
object with the value 1
.OptionalDouble optional1 = OptionalDouble.of(1.5);
ifPresent
method on the optional1
object with a DoubleConsumer
function as an argument. This function will be executed and print the value of the optional1
object.optional1.ifPresent((doubleValue)->{
System.out.println("Double Value at Optional1 is : " + doubleValue);
});
// Optional1 is. : 1.5
empty
method to get an empty OptionalDouble
object. The returned object doesn’t have any value.OptionalDouble optional2 = OptionalDouble.empty();
ifPresent
method on the optional2
object with a DoubleConsumer
function as an argument. This function will not get executed because the optional2
object 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