Skip to content

Primitive versions: no boxing needed

☕ Java 17 · The Ready-Made Lambda Toolkit · 3/4

Predicate<Integer> turns every int into an Integer object. The primitive versions work directly on the value: lighter and faster.

Int, Long, Double and Boolean versions

BooleanSupplier isLive = () -> true;
isLive.getAsBoolean();                       // true

IntSupplier episodes = () -> 8;
IntPredicate isLong = min -> min > 120;
IntUnaryOperator addAds = min -> min + 5;
DoubleBinaryOperator avg = (a, b) -> (a + b) / 2;
IntFunction<String> label = n -> "Episode " + n;

episodes.getAsInt();                         // 8
avg.applyAsDouble(8.0, 9.0);                 // 8.5
  • The prefix (Int, Long, Double) replaces the generic type: IntPredicate tests an int.
  • IntFunction<R> keeps only the return type generic.
  • When a primitive comes back, the method is renamed: getAsInt(), getAsBoolean(), applyAsDouble(), applyAsInt().

BooleanSupplier is the only interface for boolean: there is no BooleanPredicate or BooleanFunction. There are no char, float or String suppliers either.

Converting between primitives and objects

ToIntFunction<Movie> minutes = Movie::durationMinutes;
DoubleToIntFunction stars = r -> (int) Math.round(r);
ObjIntConsumer<Episode> jump = (e, sec) -> e.seek(sec);

int length = minutes.applyAsInt(dune);       // 155
int rating = stars.applyAsInt(8.6);          // 9
jump.accept(pilot, 90);                      // seek to 1:30
Family In → out Examples
ToXxxFunction<T> object → primitive ToIntFunction, ToDoubleFunction, plus Bi versions
XxxToYyyFunction primitive → other primitive DoubleToIntFunction, IntToLongFunction
ObjXxxConsumer<T> object + primitive → nothing ObjIntConsumer, ObjDoubleConsumer

You don't need to memorize every name: learn the patterns, and the name tells you the types.

Time to combine a Predicate, a Function and a Consumer in a real feature.

💻 Code: Java17_Part_8_Functional_Programming on GitHub

← Combining · Next: the lab →