The DoubleFunction<R> is a functional interface from the java.util.function package, introduced in Java 8. It accepts a primitive double value and returns a result of type R.
- Its single abstract method is apply().
- It works directly with primitive double input, avoiding boxing of the input value.
Example: Program to demonstrate DoubleFunction by converting a temperature value into a formatted String.
import java.util.function.DoubleFunction;
public class GFG {
public static void main(String[] args) {
DoubleFunction<String> temperature =
value -> value + "°C";
System.out.println(temperature.apply(25.5));
}
}
Output
25.5°C
Explanation: The lambda expression receives the primitive double value 25.5 and returns a String representing the temperature.
Syntax
The DoubleFunction<R> interface can be represented as:
@FunctionalInterface
public interface DoubleFunction<R> {
R apply(double value);
}
Here, R represents the type of the result produced by the function. The input argument is always a primitive double.
Method of DoubleFunction
The DoubleFunction interface provides one abstract method, apply(), which performs an operation using the supplied double value.
apply()
The apply() method accepts a primitive double value and returns a result of type R. It performs the specified operation using the supplied value.
Syntax:
R apply(double value)
- Parameters: value: The primitive double value supplied to the operation.
- Return Type: The method returns a value of type R.
Example: Program to use apply() to multiply a double value by 10 and return the result as an Integer.
import java.util.function.DoubleFunction;
public class GFG {
public static void main(String[] args) {
DoubleFunction<Integer> operation =
value -> (int) (value * 10);
System.out.println(operation.apply(3.2));
}
}
Output
32
Explanation: In the above example, the lambda expression provides the implementation of the apply() method. It receives the primitive double value 3.2, multiplies it by 10, and returns 32 as an Integer.
DoubleFunction vs Function
Both DoubleFunction<R> and Function<T, R> represent functions that accept one input and return a result. The main difference is that DoubleFunction specifically accepts a primitive double input.
| Feature | DoubleFunction<R> | Function<T, R> |
|---|---|---|
| First argument | Primitive double | Reference type T |
| Return type | R | R |
| Functional method | apply(double) | apply(T) |
| Generic input type | No | Yes |
| Primitive specialization | Yes | No |
Note: DoubleFunction<R> accepts a primitive double directly, while Function<Double, R> uses the Double wrapper type.
When to Use DoubleFunction?
Use DoubleFunction when an operation needs a primitive double as input and produces a result of type R. It is particularly useful when working directly with double values without requiring the input to be represented as a Double object.