Generic functional interfaces

java.util.function

Type Takes Returns
Function<T,R> T R
Predicate<T> T boolean
UnaryOperator<T> T T
BinaryOperator<T> T, T T
Consumer<T> T void
Supplier<T> no args T
BiFunction<T,U,R> T, U R
BiPredicate<T,U> T, U boolean
BiConsumer<T,U> T, U void

Unfortunately

Java’s originial sin

🐍🍎

Primitive types

In particular

What is the type of String.valueOf(int) which takes an int and returns a String?

Can’t use primitives in generic types so Function<int, String> is no good.

Answer: IntFunction<String>.

A bunch of extra types

The java.util.function package is bloated with a bunch of interfaces that exist to deal with functions (methods) that take and return primitive types.

In the alphabetical listing in the Javadocs they can be very confusing so the following slides organize them in a more useful way to show how they’re related.

Function<T,R>

But taking primitives

Type Takes Returns
DoubleFunction<R> double R
IntFunction<R> int R
LongFunction<R> long R

Function<T,R>

But returning primitives

Type Takes Returns
ToDoubleFunction<T> T double
ToIntFunction<T> T int
ToLongFunction<T> T long

Function<T,R>

But taking and returning primitive

Type Takes Returns
DoubleToIntFunction double int
DoubleToLongFunction double long
IntToDoubleFunction int double
IntToLongFunction int long
LongToDoubleFunction long double
LongToIntFunction long int

Predicate<T>

But testing primitives

Type Takes Returns
DoublePredicate double boolean
IntPredicate int boolean
LongPredicate long boolean

BiFunction<T,U,R>

But returning primitives

Type Takes Returns
ToLongBiFunction<T,U> T, U long
ToDoubleBiFunction<T,U> T, U double
ToIntBiFunction<T,U> T, U int

UnaryOperator<T>

But operating on primitives

Type Takes Returns
DoubleUnaryOperator double double
IntUnaryOperator int int
LongUnaryOperator long long

BinaryOperator<T>

But operating on primitives

Type Takes Returns
DoubleBinaryOperator double, double double
IntBinaryOperator int, int int
LongBinaryOperator long, long long

Consumer<T>

But consuming primitives

Type Takes Returns
DoubleConsumer double void
IntConsumer int void
LongConsumer long void

BiConsumer<T,U>

But consuming primitives

Type Takes Returns
ObjDoubleConsumer<T> T, double void
ObjIntConsumer<T> T, int void
ObjLongConsumer<T> T, long void

Supplier<T>

But supplying primitives

Type Takes Returns
BooleanSupplier no args boolean
DoubleSupplier no args double
IntSupplier no args int
LongSupplier no args long