ToLongFunction Interface in Java with Examples - GeeksforGeeks

ToLongFunction Interface in Java with Examples

Last Updated : 12 Sep, 2026

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.

Java
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 type T.
  • Returns: A primitive long result 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.

Java
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>

FeatureToLongFunction<T>Function<T, Long>
Input TypeGeneric type TGeneric type T
Return TypePrimitive longLong object
MethodapplyAsLong(T value)apply(T value)
Generic TypesOnly TT and Long
Primitive SpecializationYesNo

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.

Comment