Sub topic 12
Primitive Functional Interfaces and Boxing Costs
In earlier chapters you used interfaces like Function<Integer, Integer> and Predicate<Integer>. They work. But when your lambda deals with plain numbers, Java has a better choice. This chapter shows what that choice is, why it exists, and when to use it.
Why Generics Cannot Hold `int`
Java has two kinds of values:
- A primitive is a simple value such as
int,long,double, orboolean. It is stored directly, with no object around it. - A reference type is a class type, such as
StringorInteger. A variable of this type points to an object in memory.
Generics only work with reference types. You can write List<Integer>, but you cannot write List<int>. The same rule applies to functional interfaces. Function<int, int> does not compile.
So every primitive has a matching wrapper class. A wrapper class is a class whose only job is to hold one primitive value inside an object. Integer wraps int, Long wraps long, and Double wraps double.
What Boxing Is
Boxing is turning a primitive into its wrapper object, for example int into Integer. Unboxing is the reverse: taking the int back out of the Integer.
Java does both for you, without you writing any code. This is called autoboxing. It makes code easy to write, but the work still happens.
Look at this lambda:
import java.util.function.Function;
public class BoxingSteps {
public static void main(String[] args) {
Function<Integer, Integer> addOne = x -> x + 1;
int result = addOne.apply(5);
System.out.println(result); // 6
}
}Hidden inside that one call are four steps:
- The
int5 is boxed into anIntegerso it can be passed toapply. - Inside the lambda, the
Integeris unboxed so+ 1can run. - The answer, 6, is boxed into a new
Integerto be returned. - The returned
Integeris unboxed intoint result.
What Boxing Costs
Boxing has three costs.
- Time. Creating a wrapper object takes more work than copying a number. Java keeps a small cache of
Integerobjects for values from -128 to 127, but outside that range it usually makes a new object each time. - Memory. An
Integerobject uses several times more memory than a bareint. Many short-lived objects also give the garbage collector more to clean up. The garbage collector is the part of Java that frees memory you no longer use. - Null risk. A wrapper variable can be
null. A primitive never can. Unboxingnullthrows aNullPointerException.
For one call, none of this matters. In a loop that runs millions of times, it can.
The Primitive Specializations
To avoid boxing, java.util.function includes versions of the common interfaces built for int, long, and double. These are called primitive specializations. They take and return primitives directly.
Here is the same addOne with no boxing:
import java.util.function.IntUnaryOperator;
public class NoBoxing {
public static void main(String[] args) {
IntUnaryOperator addOne = x -> x + 1;
int result = addOne.applyAsInt(5);
System.out.println(result); // 6
}
}The lambda looks the same. Only the interface and the method name changed.
The Naming Pattern
The names follow a pattern, so you can usually guess them:
- A name that starts with
Int,Long, orDoublemeans the input is that primitive. - A name that starts with
ToInt,ToLong, orToDoublemeans the output is that primitive. - A method that returns a primitive gets a suffix, such as
applyAsIntorgetAsDouble. This makes it clear what comes back.
| Interface | Method | Takes | Returns | Boxed version it replaces |
|---|---|---|---|---|
| `IntPredicate` | `test` | `int` | `boolean` | `Predicate<Integer>` |
| `IntFunction<R>` | `apply` | `int` | `R` | `Function<Integer, R>` |
| `ToIntFunction<T>` | `applyAsInt` | `T` | `int` | `Function<T, Integer>` |
| `IntUnaryOperator` | `applyAsInt` | `int` | `int` | `UnaryOperator<Integer>` |
| `IntBinaryOperator` | `applyAsInt` | `int, int` | `int` | `BinaryOperator<Integer>` |
| `IntConsumer` | `accept` | `int` | nothing | `Consumer<Integer>` |
| `IntSupplier` | `getAsInt` | nothing | `int` | `Supplier<Integer>` |
| `IntToDoubleFunction` | `applyAsDouble` | `int` | `double` | `Function<Integer, Double>` |
| `ObjIntConsumer<T>` | `accept` | `T, int` | nothing | `BiConsumer<T, Integer>` |
| `ToIntBiFunction<T, U>` | `applyAsInt` | `T, U` | `int` | `BiFunction<T, U, Integer>` |
Each Int row also exists for Long and Double, for example LongPredicate and DoubleUnaryOperator. There is also BooleanSupplier with the method getAsBoolean.
A Worked Example: Test Scores
This program counts passing scores, adds a curve, and counts again. Every step works on int values with no wrappers.
import java.util.Arrays;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.ToIntFunction;
public class Scores {
static int countMatching(int[] values, IntPredicate test) {
int count = 0;
for (int v : values) {
if (test.test(v)) {
count++;
}
}
return count;
}
static int[] mapAll(int[] values, IntUnaryOperator op) {
int[] result = new int[values.length];
for (int i = 0; i < values.length; i++) {
result[i] = op.applyAsInt(values[i]);
}
return result;
}
public static void main(String[] args) {
int[] scores = {72, 95, 58, 88, 64};
IntPredicate passed = s -> s >= 60;
IntUnaryOperator curve = s -> Math.min(100, s + 5);
System.out.println(countMatching(scores, passed)); // 4
int[] curved = mapAll(scores, curve);
System.out.println(Arrays.toString(curved)); // [77, 100, 63, 93, 69]
System.out.println(countMatching(curved, passed)); // 5
ToIntFunction<String> nameLength = String::length;
System.out.println(nameLength.applyAsInt("Ada")); // 3
}
}Notice three things:
countMatchingtakes anIntPredicate, so it callstest(int). NoIntegeris ever created.mapAlltakes anIntUnaryOperator, so it callsapplyAsInt.ToIntFunction<String>takes an object and returns anint. Method references work here the same way they do with any other functional interface.
Seeing the Difference in Speed
The program below adds numbers 50 million times, once with boxed types and once with primitives.
import java.util.function.BinaryOperator;
import java.util.function.IntBinaryOperator;
public class BoxingCost {
public static void main(String[] args) {
BinaryOperator<Integer> boxedAdd = (a, b) -> a + b;
IntBinaryOperator primitiveAdd = (a, b) -> a + b;
int n = 50_000_000;
long start = System.nanoTime();
Integer boxedTotal = 0;
for (int i = 0; i < n; i++) {
boxedTotal = boxedAdd.apply(boxedTotal, i % 10);
}
long boxedMs = (System.nanoTime() - start) / 1_000_000;
start = System.nanoTime();
int primitiveTotal = 0;
for (int i = 0; i < n; i++) {
primitiveTotal = primitiveAdd.applyAsInt(primitiveTotal, i % 10);
}
long primitiveMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("Boxed: " + boxedTotal + " in " + boxedMs + " ms");
System.out.println("Primitive: " + primitiveTotal + " in " + primitiveMs + " ms");
}
}Both totals print 225000000. The times depend on your computer and Java version, and Java's optimizer can sometimes remove part of the boxing cost. The primitive loop is usually faster.
Common Mistakes
Unboxing null
A boxed interface accepts null, and the program fails only when it runs. A primitive interface rejects null when you compile.
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
public class NullUnboxing {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;
System.out.println(square.apply(4)); // 16
try {
square.apply(null);
} catch (NullPointerException e) {
System.out.println("NullPointerException: null cannot be unboxed");
}
IntUnaryOperator squareInt = x -> x * x;
System.out.println(squareInt.applyAsInt(4)); // 16
// squareInt.applyAsInt(null); // does not compile
}
}Mixing the two families
IntPredicate is not a Predicate<Integer>. They are separate interfaces, and you cannot pass one where the other is expected. A method reference converts between them:
import java.util.function.IntPredicate;
import java.util.function.Predicate;
public class Convert {
public static void main(String[] args) {
IntPredicate isEven = n -> n % 2 == 0;
Predicate<Integer> boxedIsEven = isEven::test; // unboxes each call
System.out.println(boxedIsEven.test(4)); // true
}
}Using the wrong method name
IntUnaryOperator has no apply method. It has applyAsInt. If the compiler says it "cannot find symbol apply", check the table above for the correct name.
Composition Still Works
The primitive interfaces have the same kinds of default methods you saw for composing functions. IntPredicate has and, or, and negate. IntUnaryOperator has andThen and compose.
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
public class PrimitiveCompose {
public static void main(String[] args) {
IntPredicate positive = n -> n > 0;
IntPredicate even = n -> n % 2 == 0;
System.out.println(positive.and(even).test(6)); // true
IntUnaryOperator doubleIt = x -> x * 2;
IntUnaryOperator addThree = x -> x + 3;
System.out.println(doubleIt.andThen(addThree).applyAsInt(5)); // 13
}
}Exercise
You need a lambda that takes a String and returns its number of vowels as an int, with no boxing of the result. Which interface do you use, and which method do you call on it?
Show answer
ToIntFunction<String>, because the input is an object (String) and the output is a primitive int. You call applyAsInt, for example: ToIntFunction<String> vowels = s -> s.replaceAll("[^aeiouAEIOU]", "").length(); then vowels.applyAsInt("lambda") returns 2.
Exercise
How many boxing or unboxing steps happen in this code, and what is the primitive version? Supplier<Integer> dice = () -> 4; int roll = dice.get();
Show answer
Two steps. The int 4 is boxed into an Integer when the lambda returns it, and that Integer is unboxed when it is assigned to int roll. The primitive version is IntSupplier dice = () -> 4; int roll = dice.getAsInt(); which has no boxing.
Exercise
Why does this line fail to compile, and how do you fix it? IntBinaryOperator max = (a, b) -> Math.max(a, b); int m = max.apply(3, 7);
Show answer
IntBinaryOperator has no method named apply. Its method is applyAsInt, because it returns a primitive int. The fix is int m = max.applyAsInt(3, 7); which gives 7.