What is the difference between Predicate, Function, Consumer and Supplier in Java?
They are four shapes of function, and each one has a different number of inputs and outputs.
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
// A predicate: one value in, a yes or a no out.
Predicate<String> isLong = text -> text.length() > 3;
System.out.println("is long : " + isLong.test("hello"));
// A function: one value in, one value out.
Function<String, Integer> length = text -> text.length();
System.out.println("length : " + length.apply("hello"));
// A consumer: one value in, nothing out.
Consumer<String> printer = text -> System.out.println("printed : " + text);
printer.accept("hello");
// A supplier: nothing in, one value out.
Supplier<String> greeting = () -> "hello";
System.out.println("greeting : " + greeting.get());
}
}
So here is the difference in one line each. A Predicate takes one value and gives back a boolean, and its method is called test. A Function takes one value and gives back a different value, and its method is called apply. A Consumer takes one value and gives nothing back at all, and its method is called accept. A Supplier takes nothing at all and gives back a value, and its method is called get.
There are also versions that take two values, such as BiFunction and BiConsumer, and versions that take a primitive and give back a primitive, such as IntFunction and IntPredicate. They all follow the same pattern.
The next question in this topic sorts them out by what they give back.