The ToLongFunction<T> is a functional interface from the java.util.function package, introduced in Java 8. It represents a function that accepts an argument of type T and produces a primitive long result.
- T represents the type of the input argument.
- Its single abstract method is applyAsLong(), which applies the defined operation and returns a long value.
- It is similar to Function<T, Long>, but ToLongFunction<T> directly produces a primitive long result.
Example: Program To demonstrates how ToLongFunction<String> accepts a String value and calculates its length as a primitive long.
import java.util.function.ToLongFunction;
public class GFG {
public static void main(String[] args) {
ToLongFunction<String> operation =
value -> value.length();
System.out.println(operation.applyAsLong("GeeksForGeeks"));
}
}
Output
13
Explanation: The ToLongFunction<String> accepts "GeeksForGeeks" as input and calculates its length. The applyAsLong() method returns the length as a primitive long value.
Syntax
@FunctionalInterfacepublic
interface ToLongFunction<T> {
long applyAsLong(T value);}
Method Of ToLongFunction
The ToLongFunction<T> interface provides one abstract method, applyAsLong(), which accepts a value of type T and returns a primitive long result.
applyAsLong()
The applyAsLong() method applies the defined operation to the supplied input and returns the result as a primitive long.
Syntax
long applyAsLong(T value);
- Parameters:
value: The input argument of typeT. - Returns: A primitive
longresult produced by the operation.
Example: Program to demonstrates how ToLongFunction<Integer> accepts an Integer value and produces a long result by multiplying it by 10,000.
import java.util.function.ToLongFunction;
public class GFG {
public static void main(String[] args) {
ToLongFunction<Integer> operation =
value -> value * 10000L;
System.out.println(operation.applyAsLong(3));
}
}
Output
30000
Explanation: The ToLongFunction<Integer> accepts 3 as an Integer input. The lambda expression multiplies it by 10,000, and applyAsLong() returns the result as a primitive long.
ToLongFunction<T> and Function<T, Long>
| Feature | ToLongFunction<T> | Function<T, Long> |
|---|---|---|
| Input Type | Generic type T | Generic type T |
| Return Type | Primitive long | Long object |
| Method | applyAsLong(T value) | apply(T value) |
| Generic Types | Only T | T and Long |
| Primitive Specialization | Yes | No |
When to Use ToLongFunction?
Use ToLongFunction<T> when an operation accepts an input of type T and produces a primitive long result. It is particularly useful when working with long results without requiring the result to be represented as a Long object.