The Plain Picture#
A sticky note needs a slot to fit into. A "comparison" slot accepts notes that take two things and return a number. A "yes/no check" slot accepts notes that take one thing and return true or false. The slot's shape decides which notes fit.
The Real Names#
A functional interface is an interface with exactly one abstract method (
defaultandstaticmethods don't count). A lambda can be used anywhere a functional interface is expected — the lambda becomes that one method's body.@FunctionalInterfaceis an optional annotation that makes the compiler check there's exactly one abstract method.You already know several:
Comparator<T>(compare),Runnable(run),Comparable<T>(compareTo).
The standard ones in java.util.function — memorise the first six:
| Interface | Method | Takes → Returns | Example |
|---|---|---|---|
Predicate<T> | test | T → boolean | s -> s >= 150 |
Function<T, R> | apply | T → R | s -> s >= 200 ? "A" : "B" |
Consumer<T> | accept | T → nothing | msg -> System.out.println(msg) |
Supplier<T> | get | nothing → T | () -> new ArrayList<>() |
BiFunction<T, U, R> | apply | (T, U) → R | (a, b) -> a + b |
UnaryOperator<T> | apply | T → T | s -> s.trim() |
BinaryOperator<T> | apply | (T, T) → T | Integer::sum |
BiConsumer, BiPredicate | two inputs | map.forEach((k, v) -> ...) | |
IntPredicate, IntFunction, ToIntFunction, IntBinaryOperator… | primitive versions — no boxing | ToIntFunction<Student> f = Student::score |
Under the Hood#
Predicate<Integer> passing = s -> s >= 150;
Function<Integer, String> grade = s -> s >= 200 ? "A" : s >= 150 ? "B" : "C";
Consumer<String> shout = msg -> System.out.println(msg.toUpperCase());
Supplier<List<String>> fresh = ArrayList::new;
BiFunction<Integer, Integer, Integer> add = Integer::sum;
UnaryOperator<String> trim = String::trim;
System.out.println(
passing.test(180) +
" " +
grade.apply(160) +
" " +
add.apply(2, 3) +
" [" +
trim.apply(" hi ") +
"] " +
fresh.get().size()
);
// true B 5 [hi] 0
shout.accept("well done"); // WELL DONEThey compose through default methods:
passing.negate().test(180) // false
passing.and(s -> s < 200).test(199) // true
grade.andThen(g -> g + "!").apply(210) // A!Why this matters: functional interfaces let you pass behaviour as a parameter — the strategy idea from SOLID Principles Ch 3 without
writing a class per strategy. CreditRule could simply be a UnaryOperator<Integer>.
Check yourself
3 questionsWhat makes an interface "functional"?
Show answerHide answer
It has exactly one abstract method.
Which functional interface fits: "is this note empty?"; "turn a score into a grade"; "create a new cache"; "log a message"?
Show answerHide answer
Predicate<Note>; Function<Integer, String>; Supplier<Cache>; Consumer<String>.
Is Comparator a functional interface even though it has many methods?
Show answerHide answer
Yes — it has one abstract method (compare); the others are default or static (equals from Object doesn't count either).