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 anint, returns an object of typeRLongFunction<R>– accepts along, returns an object of typeRDoubleFunction<R>– accepts adouble, returns an object of typeR
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.