Card 08/ 09
Practice: Naming the Interface Each Lambda Implements
Five lambdas in real calls; for each, name the interface and the method it supplies.
A lambda's interface comes from the parameter it is passed to, and the four core shapes are separated by what goes in and what comes out. For each of the five lambdas below, name the functional interface, the one-method interface, it lands in and the method it supplies, all five before opening the answer.
// 1
names.removeIf(n -> n.isBlank());
// 2
names.replaceAll(n -> n.trim());
// 3
names.forEach(n -> System.out.println(n));
// 4
names.sort((a, b) -> a.length() - b.length());
// 5
Optional.ofNullable(cached).orElseGet(() -> load());The five interfaces, and the method each lambda supplies
| Interface | Method | Shape | |
|---|---|---|---|
| 1 | Predicate<String> | test | Takes one, returns a boolean |
| 2 | UnaryOperator<String> | apply | Takes one, returns the same type |
| 3 | Consumer<String> | accept | Takes one, returns nothing |
| 4 | Comparator<String> | compare | Takes two, returns an int |
| 5 | Supplier<String> | get | Takes nothing, returns one |
None of the five said what it was. Each one's type came from the parameter it was handed to, which is the thing worth being able to read off a call site.
Number four also shows a habit worth dropping. Subtracting two lengths is safe, because lengths are never negative, but subtraction as a comparator overflows on large values of opposite sign. Comparator.comparingInt(String::length) is clearer and is correct for any int.
← → move through sections and cards