Course contentsShow
← Java
Lesson 1695 of 2,87035. Functional InterfacesFree lesson

IntSupplier, LongSupplier, DoubleSupplier, and BooleanSupplier

Explore suppliers that produce primitive values directly without wrapper objects.

IntSupplier, LongSupplier, DoubleSupplier, and BooleanSupplier

What you'll learn: How to supply primitive values efficiently without the overhead of wrapper objects.

The Problem with Generic Supplier<T>

You've learned about Supplier<T>, which uses the generic get() method to return any object type. But when you need Supplier<Integer>, Java must wrap primitive int values in Integer objects—this boxing creates unnecessary overhead when you're generating many primitive values.

The Primitive Supplier Interfaces

Java provides specialized supplier interfaces that return primitives directly:

  • IntSupplier - supplies int values via getAsInt()
  • LongSupplier - supplies long values via getAsLong()
  • DoubleSupplier - supplies double values via getAsDouble()
  • BooleanSupplier - supplies boolean values via getAsBoolean()

These interfaces avoid boxing by returning primitive types directly.

Basic Examples

IntSupplier randomDieRoll = () -> (int)(Math.random() * 6) + 1;
int roll = randomDieRoll.getAsInt(); // Returns primitive int

LongSupplier timestamp = () -> System.currentTimeMillis();
long time = timestamp.getAsLong(); // Returns primitive long

DoubleSupplier temperature = () -> 98.6;
double temp = temperature.getAsDouble(); // Returns primitive double

BooleanSupplier coinFlip = () -> Math.random() > 0.5;
boolean heads = coinFlip.getAsBoolean(); // Returns primitive boolean

Performance Advantage

Each primitive supplier eliminates autoboxing overhead. When generating thousands of values, this makes a measurable difference in both speed and memory usage.

// Avoid: Supplier<Integer> boxes every value
Supplier<Integer> boxed = () -> 42;
Integer wrapped = boxed.get(); // Creates Integer object

// Prefer: IntSupplier returns raw primitive
IntSupplier primitive = () -> 42;
int raw = primitive.getAsInt(); // No object creation

Key Takeaway: Use IntSupplier, LongSupplier, DoubleSupplier, and BooleanSupplier when generating primitive values to avoid boxing overhead and improve performance.