Video in progress
How do the Function, Consumer, Supplier and Predicate interfaces differ from each other?
The difference is in input and output: Function<T,R> takes T and returns R; Consumer<T> takes a value and returns nothing; Supplier<T> takes nothing and gives T; Predicate<T> takes a value and returns boolean.
📖 Answer
They're easy to remember if you look at the method signature:
| Interface | Method | Example |
|---|---|---|
Function<T, R> |
R apply(T t) |
String::length |
Consumer<T> |
void accept(T t) |
System.out::println |
Supplier<T> |
T get() |
ArrayList::new |
Predicate<T> |
boolean test(T t) |
String::isBlank |
Predicate<String> notEmpty = s -> !s.isEmpty();
Function<String, Integer> len = String::length;
Consumer<String> log = s -> System.out.println("> " + s);
Supplier<LocalDate> today = LocalDate::now;
There are two-argument variants too: BiFunction, BiConsumer, BiPredicate. When the input and output types are the same, there are UnaryOperator<T> and BinaryOperator<T>.
In streams they're everywhere: filter takes a Predicate, map takes a Function, forEach takes a Consumer, generate takes a Supplier.
Sign up to mark studied questions and save your progress.