The LongToDoubleFunction is a functional interface from the java.util.function package, introduced in Java 8. It accepts a primitive long value and returns a primitive double result.
- Its single abstract method is applyAsDouble().
- It avoids boxing and unboxing by working directly with primitive values.
Example: Program to demonstrate LongToDoubleFunction by converting a distance from meters to kilometers.
import java.util.function.LongToDoubleFunction;
public class GFG {
public static void main(String[] args) {
LongToDoubleFunction metersToKilometers =
meters -> meters / 1000.0;
System.out.println(
metersToKilometers.applyAsDouble(5000L)
);
}
}
Output
5.0
Explanation: The lambda expression receives 5000L meters and divides it by 1000.0. The resulting value, 5.0, is returned as a primitive double.
Syntax
The LongToDoubleFunction interface can be represented as:
@FunctionalInterface
public interface LongToDoubleFunction {
double applyAsDouble(long value);
}
Here, the function takes a primitive long as input and returns a primitive double.
Method Of LongToDoubleFunction
The LongToDoubleFunction interface provides one abstract method, applyAsDouble(), which accepts a primitive long value and returns a primitive double result.
applyAsDouble()
The applyAsDouble() method receives a primitive long value, applies the function logic, and returns the computed result as a primitive double.
Syntax
double applyAsDouble(long value);
- Parameter: value – the primitive long value supplied to the function.
- Return Type: Returns the calculated result as a primitive double.
Example: Program to use applyAsDouble() to calculate the average of a given value and 10.
import java.util.function.LongToDoubleFunction;
public class GFG {
public static void main(String[] args) {
LongToDoubleFunction operation =
value -> (value + 10) / 2.0;
System.out.println(operation.applyAsDouble(20L));
}
}
Output
15.0
Explanation: The lambda receives 20L, adds 10, and divides the result by 2.0. The expression produces 15.0, which is returned as a primitive double.
Why Use LongToDoubleFunction?
LongToDoubleFunction is useful when an operation takes a primitive long value and produces a primitive double result. It is especially suitable for numerical calculations and unit conversions where decimal results are required. Unlike Function<Long, Double>, it works directly with primitive values instead of wrapper types.
LongToDoubleFunction vs Function<Long, Double>
| Feature | LongToDoubleFunction | Function<Long, Double> |
|---|---|---|
| Input Type | Primitive long | Long |
| Return Type | Primitive double | Double |
| Method | applyAsDouble(long) | apply(Long) |
| Generic Types | None | Long and Double |
| Primitive Specialization | Yes | No |