Primitive functional interfaces
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Generic interfaces such as Predicate<Integer> work only with objects, so every int must be wrapped in an Integer first. Primitive functional interfaces such as IntPredicate take and return plain int, long or double values, with no wrapping at all.
Why boxing costs time and memory
Boxing means wrapping a primitive value in an object, such as int 1000 in an Integer. Unboxing is the reverse. Java does both automatically, and each one costs time and memory.
A Function<Integer, Integer> square = n -> n * n hides a cost: each call unboxes the input and boxes the result. An Integer is a separate heap object, usually 16 bytes, while an int is 4 bytes stored in the variable.
Example 1 · Boxed versus primitive: same answer, different cost
import java.util.function.Function;import java.util.function.IntUnaryOperator;
public class BoxingDemo { public static void main(String[] args) { Function<Integer, Integer> boxedSquare = n -> n * n; IntUnaryOperator square = n -> n * n;
long boxedSum = 0; long plainSum = 0; for (int i = 1; i <= 1_000; i++) { boxedSum += boxedSquare.apply(i); // box i, unbox, box the result, unbox again plainSum += square.applyAsInt(i); // plain int in, plain int out } System.out.println("Boxed sum: " + boxedSum); System.out.println("Plain sum: " + plainSum);
Integer missing = null; // for example, a student with no marks entered try { boxedSquare.apply(missing); } catch (NullPointerException e) { System.out.println("Boxed lambda with null: " + e.getClass().getSimpleName()); } }}Boxed sum: 333833500 Plain sum: 333833500 Boxed lambda with null: NullPointerException
What this code does
- Both loops print the same sum. The difference is hidden: the
Function<Integer, Integer>version wraps values above 127 in newIntegerobjects on every call, whileIntUnaryOperatorworks on plainintvalues. - A boxed lambda can receive
null, andn * nmust unbox it, which throwsNullPointerException.square.applyAsInt(null)would not even compile, becausenullis not anint.
Each Integer also needs a reference to reach it, and Java keeps ready-made objects only for -128 to 127, so most values need a new object. In a loop over a million readings, that is up to a million small objects for the garbage collector to clean up.
There is a second cost: an Integer can be null. Passing null to a boxed lambda that does arithmetic throws NullPointerException. A plain int can never be null, so the primitive versions cannot fail that way.
comparingInt.The Int family: IntPredicate, IntFunction and the operators
For each core shape there is an int version. The input is a plain int, so these interfaces need fewer type arguments, often none.
Example 2 · The Int family in one program
import java.util.function.IntBinaryOperator;import java.util.function.IntConsumer;import java.util.function.IntFunction;import java.util.function.IntPredicate;import java.util.function.IntSupplier;import java.util.function.IntUnaryOperator;
public class IntFamilyDemo { public static void main(String[] args) { IntPredicate isEven = n -> n % 2 == 0; IntUnaryOperator addGrace = m -> Math.min(100, m + 3); IntBinaryOperator larger = (a, b) -> a >= b ? a : b; IntFunction<String> stars = r -> "*".repeat(r); IntSupplier maxMarks = () -> 100; IntConsumer showScore = s -> System.out.println("Score: " + s);
System.out.println("14 even? " + isEven.test(14)); System.out.println("98 + grace = " + addGrace.applyAsInt(98)); System.out.println("Better of 71 and 84: " + larger.applyAsInt(71, 84)); System.out.println("Rating 4: " + stars.apply(4)); System.out.println("Out of " + maxMarks.getAsInt()); showScore.accept(84); }}14 even? true 98 + grace = 100 Better of 71 and 84: 84 Rating 4: **** Out of 100 Score: 84
What this code does
- None of these needs
<Integer>: the input is fixed asint. OnlyIntFunction<String>has a type argument, because its result is an object. - Methods that return a primitive have names ending in
AsInt:applyAsInt,getAsInt.test,applyandacceptkeep their usual names.
IntPredicate:boolean test(int value).IntConsumer:void accept(int value).IntFunction<R>:R apply(int value), from anintto any object, such as aString.IntUnaryOperator:int applyAsInt(int operand).IntSupplier:int getAsInt().IntBinaryOperator:int applyAsInt(int left, int right), to combine twoints.
When the result is a primitive, the method name says so: applyAsInt, getAsInt, applyAsDouble. The different names let one class implement several of these interfaces without its methods clashing. The same families exist for long and double: LongPredicate, DoubleUnaryOperator, DoubleBinaryOperator and so on. There are no char, short, byte or float versions; use the int or double ones, since those smaller types widen to them automatically.
ToIntFunction and ToDoubleFunction: object in, number out
Often the input is an object and only the result is a number: the price of a product, the length of a name, the CGPA of a student. ToIntFunction<T> has int applyAsInt(T value); ToDoubleFunction<T> and ToLongFunction<T> do the same for double and long.
Example 3 · ToIntFunction and ToDoubleFunction: comparingInt and your own total
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.function.ToDoubleFunction;import java.util.function.ToIntFunction;
record Product(String name, int price, double rating) {}
public class ToIntFunctionDemo { static <T> int total(List<T> items, ToIntFunction<T> amount) { int sum = 0; for (T item : items) { sum += amount.applyAsInt(item); } return sum; }
public static void main(String[] args) { List<Product> cart = new ArrayList<>(List.of( new Product("Earphones", 1299, 4.1), new Product("Notebook", 60, 4.6), new Product("Charger", 899, 3.9)));
ToIntFunction<Product> price = p -> p.price(); ToDoubleFunction<Product> rating = p -> p.rating();
cart.sort(Comparator.comparingInt(price)); System.out.println("Cheapest first: " + cart.get(0).name() + ", " + cart.get(1).name() + ", " + cart.get(2).name()); cart.sort(Comparator.comparingDouble(rating).reversed()); System.out.println("Best rated: " + cart.get(0).name()); System.out.println("Cart total: Rs. " + total(cart, price)); }}Cheapest first: Notebook, Charger, Earphones Best rated: Notebook Cart total: Rs. 2258
What this code does
comparingInttakes aToIntFunction<Product>andcomparingDoubletakes aToDoubleFunction<Product>. Storing them in typed variables first also lets.reversed()compile.totalworks for any typeT: the caller passes how to read the number. It adds plainintvalues, with noIntegerobjects in between.
You already used them. Comparator.comparingInt(p -> p.price()) takes a ToIntFunction<T>, and comparingDouble takes a ToDoubleFunction<T>. They read each key as a plain number and compare with Integer.compare or Double.compare, with no boxing. Your own methods can take them too. static <T> int total(List<T> items, ToIntFunction<T> amount) can add up fees, prices or marks from any kind of record, and it returns a plain int.
Reading the naming pattern
There are 43 interfaces in java.util.function, but the names follow a few rules. Once you know them, you can read any name without looking it up.
Example 4 · Decoding names: ObjIntConsumer, IntToDoubleFunction, ToIntBiFunction
import java.util.function.DoubleUnaryOperator;import java.util.function.IntToDoubleFunction;import java.util.function.ObjIntConsumer;import java.util.function.ToIntBiFunction;
public class NamingDemo { public static void main(String[] args) { // Obj + Int + Consumer: an object and an int in, nothing out ObjIntConsumer<String> printRank = (name, rank) -> System.out.println(rank + ". " + name); printRank.accept("Kavya", 1); printRank.accept("Rohan", 2);
// Int + To + Double: an int in, a double out IntToDoubleFunction toPercent = marks -> marks * 100.0 / 120; System.out.println("96 out of 120 = " + toPercent.applyAsDouble(96) + "%");
DoubleUnaryOperator withGst = amount -> amount * 1.18; System.out.println("Rs. 250 with GST = " + withGst.applyAsDouble(250));
// To + Int + Bi + Function: two objects in, an int out ToIntBiFunction<String, String> totalLength = (a, b) -> a.length() + b.length(); System.out.println("Letters in full name: " + totalLength.applyAsInt("Arjun", "Mehta")); }}1. Kavya 2. Rohan 96 out of 120 = 80.0% Rs. 250 with GST = 295.0 Letters in full name: 10
What this code does
- Read each name from left to right: the leading primitive is the input,
To+ primitive is the result,Objmeans one input is an object, andBimeans two inputs. 250 * 1.18prints295.0becausewithGstworks withdoublevalues. Theint250 is widened todoublewhen it is passed in.
- A primitive at the start is the input type:
IntPredicatetests anint,DoubleUnaryOperatorchanges adouble. To+ a primitive is the result type:ToIntFunction<T>gives anint,IntToDoubleFunctionturns anintinto adouble.Obj+ a primitive means one object input and one primitive input:ObjIntConsumer<T>hasaccept(T t, int value).Bimeans two inputs:ToIntBiFunction<T, U>takes two objects and returns anint.
BooleanSupplier with getAsBoolean(). Predicates already return a plain boolean, so no other boolean versions are needed.Common mistake: mixing Predicate<Integer> and IntPredicate
Predicate<Integer> and IntPredicate are two separate interfaces. Neither extends the other, so a variable of one type cannot be passed where the other is expected. The compiler says "incompatible types: Predicate<Integer> cannot be converted to IntPredicate".
Example 5 · Mistake: passing a Predicate<Integer> where an IntPredicate is needed
import java.util.function.Predicate;import java.util.function.IntPredicate;
public class MixedPredicateDemo { static int countIf(int[] values, IntPredicate rule) { int count = 0; for (int v : values) { if (rule.test(v)) { count++; } } return count; }
public static void main(String[] args) { int[] temps = {41, 38, 44, 36, 42}; Predicate<Integer> heatwave = t -> t >= 40; System.out.println("Heatwave days: " + countIf(temps, heatwave)); }}MixedPredicateDemo.java:18: error: incompatible types: Predicate<Integer> cannot be converted to IntPredicate
System.out.println("Heatwave days: " + countIf(temps, heatwave));
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorWhat this code does
Predicate<Integer>andIntPredicateare unrelated interfaces, so the declared variableheatwavecannot be converted, even though its lambda would fit both.- Fix it by declaring
IntPredicate heatwave = t -> t >= 40;(the best choice here), or by wrapping it:countIf(temps, t -> heatwave.test(t)). A lambda written straight in the call,countIf(temps, t -> t >= 40), also works.
This happens when a rule is written once as Predicate<Integer> and later passed to a method that takes IntPredicate, or the other way round. A lambda written directly in the call works with both, because Java builds whichever interface the parameter needs. It is the declared variable that has a fixed type. Fixes: declare the variable with the type the method wants, or wrap it in a small lambda, x -> rule.test(x), which Java turns into the needed interface. Be consistent: in number-heavy code, use the primitive types everywhere.
Fix the error
Fix the mixed-up interface
Read the real compiler error, then pick the line that fixes it.
check expects an IntPredicate. Declare the rule so it fits.
Error
PrimFix.java:9: error: incompatible types: Predicate<Integer> cannot be converted to IntPredicate
System.out.println(check(even, 8));Next step
Check your understanding
12 quick questions