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 OptionalDouble object is a container object that may or may not contain a double value. The OptionalDouble class is present in the java.util package.

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 OptionalDouble class.
import java.util.OptionalDouble;
  • In line 5, we use the of method to create an OptionalDouble object with the value 1.
OptionalDouble optional1 = OptionalDouble.of(1.5);
  • In line 6, we call the 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 
  • In line 10, we use the empty method to get an empty OptionalDouble object. The returned object doesn’t have any value.
OptionalDouble optional2 = OptionalDouble.empty();
  • In line 11, we call the 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

Free Resources