The java.util.function catalogue
Pick the right built-in interface instead of inventing your own for every callback.
Open this lesson in the learning hubKey points
- Java 8 shipped ~43 interfaces in
java.util.functionso libraries would stop inventing incompatible ones. - Four carry almost all the weight:
Function,Predicate,Consumer,Supplier. - Choose by shape: what goes in, what comes out. That is the only question.
- Primitive variants like
IntPredicateexist purely to avoid boxing in hot loops. @FunctionalInterfaceis optional but makes the compiler reject a second abstract method.
Example
import java.util.function.*;
public class Main {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
Predicate<String> isLong = s -> s.length() > 4;
Consumer<String> print = s -> System.out.println(" consumed: " + s);
Supplier<String> make = () -> "generated";
System.out.println("Function : " + length.apply("streams"));
System.out.println("Predicate : " + isLong.test("hi"));
print.accept("a value");
System.out.println("Supplier : " + make.get());
// BiFunction takes two arguments
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println("BiFunction: " + add.apply(2, 3));
// UnaryOperator is a Function whose input and output types match
UnaryOperator<String> shout = s -> s.toUpperCase();
System.out.println("UnaryOp : " + shout.apply("quiet"));
}
}
Ask what goes in and what comes out - the answer names the interface.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.