Java 8 | LongSupplier Interface with Examples

Last Updated : 20 Jun, 2026

The LongSupplier interface is a specialized functional interface introduced in Java 8 and available in the java.util.function package. It represents a supplier of long values and does not accept any input arguments. It is commonly used when a long value needs to be generated, computed, or supplied on demand.

  • Primitive specialization of Supplier<Long>.
  • Avoids boxing and unboxing overhead.
  • Supports lambda expressions and method references.
Java
import java.util.function.LongSupplier;

public class Main {
    public static void main(String[] args) {

        LongSupplier randomNumber =
            () -> (long) (Math.random() * 100);

        System.out.println(randomNumber.getAsLong());
    }
}

Output
47

Explanation: In this example, the LongSupplier generates a random long value between 0 and 99. The getAsLong() method retrieves and returns the generated value.

Syntax

@FunctionalInterface
public interface LongSupplier

Methods of LongSupplier Interface

1. getAsLong() Method

The getAsLong() method is the functional method of the LongSupplier interface. It does not accept any arguments and returns a primitive long value.

  • Core method of the interface.
  • Returns a primitive long.
  • Takes no input parameters.

Syntax:

long getAsLong()

Return Value: Returns a long value.

Example 1: Generate a Random Long Value

Java
import java.util.function.LongSupplier;

public class Main {
    public static void main(String[] args) {

        LongSupplier randomValue =
            () -> (long) (Math.random() * 1000);

        System.out.println(randomValue.getAsLong());
    }
}

Output
591

Explanation: The supplier generates and returns a random long value. Each call to getAsLong() may produce a different result.

Example 2: Return Current Time

Java
import java.util.function.LongSupplier;

public class Main {
    public static void main(String[] args) {

        LongSupplier currentTime =
            () -> System.currentTimeMillis();

        System.out.println(currentTime.getAsLong());
    }
}

Output
1781936346232

Explanation: The supplier returns the current system time in milliseconds using System.currentTimeMillis().

LongSupplier vs Supplier<Long>

FeatureLongSupplierSupplier
Return TypelongLong
Input ArgumentsNoneNone
Boxing/UnboxingNot RequiredRequired
PerformanceFasterSlightly Slower
Packagejava.util.functionjava.util.function

Advantages of LongSupplier

  • Avoids boxing and unboxing of Long objects.
  • Improves performance when working with primitive long values.
  • Supports lambda expressions and method references.
  • Useful for generating timestamps, IDs, and numeric values.
  • Simplifies functional-style programming.
  • Ideal for lazy evaluation and value generation.
Comment