Card 04/ 09

ComparisonDifficulty: Intermediate1 min

Function, Predicate, Consumer and Supplier on Two Axes

Rather than a new interface for every job, the library ships a handful of general ones. Four of them cover almost everything, and they are separated by two questions: does it take something, and does it give something back.

The four core functional interfaces, by what they take and give
InterfaceTakesGives backThe methodWritten as
Function<T, R>A TAn Rapplys -> s.length()
Predicate<T>A TA booleantests -> s.isBlank()
Consumer<T>A TNothingaccepts -> System.out.println(s)
Supplier<T>NothingA Tget() -> new ArrayList<>()

The decision rule. Work out what goes in and what comes out and the interface is decided. A Predicate is only a Function that returns a boolean, and it exists separately because filtering is common enough to deserve a name and and, or and negate to combine with.

Two variants turn up constantly. BiFunction<T, U, R> takes two arguments, and UnaryOperator<T> is a Function whose input and output are the same type — which is what List.replaceAll wants.