The DoubleSupplier interface is a specialized functional interface introduced in Java 8 and available in the java.util.function package. It represents a supplier of double values and does not accept any input arguments. It is commonly used when a double value needs to be generated, computed, or supplied on demand.
- Primitive specialization of Supplier<Double>.
- Avoids boxing and unboxing overhead.
- Supports lambda expressions and method references.
import java.util.function.DoubleSupplier;
public class Main {
public static void main(String[] args) {
DoubleSupplier randomValue =
() -> Math.random();
System.out.println(randomValue.getAsDouble());
}
}
Output
0.08957323531712014
Explanation: In this example, the DoubleSupplier generates a random double value using Math.random(). The getAsDouble() method is used to retrieve the generated value.
Syntax
@FunctionalInterface
public interface DoubleSupplier
Methods of DoubleSupplier Interface
1. getAsDouble() Method
The getAsDouble() method is the functional method of the DoubleSupplier interface. It does not take any arguments and returns a double value.
- Returns a primitive double value.
- Does not accept any input parameters.
Syntax:
double getAsDouble()
Return Value: Returns a double value.
import java.util.function.DoubleSupplier;
public class Main {
public static void main(String[] args) {
DoubleSupplier random =
() -> Math.random();
System.out.println(random.getAsDouble());
}
}
Output
0.7888683342937106
Explanation: The DoubleSupplier generates and returns a random double value between 0.0 and 1.0 each time getAsDouble() is called.
Example 2: Return Circle Area
import java.util.function.DoubleSupplier;
public class Main {
public static void main(String[] args) {
double radius = 5.0;
DoubleSupplier area =
() -> 3.14 * radius * radius;
System.out.println(area.getAsDouble());
}
}
Output
78.5
Explanation: The supplier calculates the area of a circle using a predefined radius and returns the result as a double value.
DoubleSupplier vs Supplier<Double>
| Feature | DoubleSupplier | Supplier |
|---|---|---|
| Return Type | double | Double |
| Input Arguments | None | None |
| Boxing/Unboxing | Not Required | Required |
| Performance | Faster | Slightly Slower |
| Package | java.util.function | java.util.function |
Advantages of DoubleSupplier
- Avoids boxing and unboxing of Double objects.
- Improves performance when working with primitive double values.
- Useful for generating random numbers and calculated values.
- Supports lambda expressions and method references.
- Simplifies code in functional programming.