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

IntFunction, LongFunction, and DoubleFunction

Explore functions that accept primitive inputs and return objects without boxing.

IntFunction, LongFunction, and DoubleFunction

You'll learn how to transform primitive values into objects efficiently without unnecessary boxing.

The Boxing Problem

When you need a function that accepts a primitive input (like int, long, or double) and returns an object, using Function<Integer, R> forces Java to box the primitive into a wrapper object. This creates unnecessary overhead.

The Primitive-to-Object Solution

Java provides specialized functional interfaces that accept primitive inputs directly:

  • IntFunction<R> – accepts an int, returns an object of type R
  • LongFunction<R> – accepts a long, returns an object of type R
  • DoubleFunction<R> – accepts a double, returns an object of type R

Each has a single abstract method: R apply(int value), R apply(long value), or R apply(double value).

When to Use Them

Use these when you're working with primitive streams or collections of primitives and need to convert them to objects:

IntFunction<String> intToHex = value -> Integer.toHexString(value);
String hex = intToHex.apply(255); // "ff"

LongFunction<String> longToTimestamp = timestamp -> 
    java.time.Instant.ofEpochMilli(timestamp).toString();

DoubleFunction<String> doubleToPercent = value -> 
    String.format("%.2f%%", value * 100);

Think of It This Way

Imagine a vending machine that only accepts exact coins (primitives) but dispenses wrapped products (objects). These specialized functions are like coin slots designed for specific denominations—faster than having to convert your coins to bills first, then back to coins.

Key Takeaway: IntFunction, LongFunction, and DoubleFunction accept primitive inputs and return objects without boxing, improving performance when transforming primitive values into reference types.