Card 04/ 09
All 9 cards
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.
| Interface | Takes | Gives back | The method | Written as |
|---|---|---|---|---|
Function<T, R> | A T | An R | apply | s -> s.length() |
Predicate<T> | A T | A boolean | test | s -> s.isBlank() |
Consumer<T> | A T | Nothing | accept | s -> System.out.println(s) |
Supplier<T> | Nothing | A T | get | () -> 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.