Card 08/ 09

ExerciseDifficulty: Advanced1 min

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.

java
// 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
Each lambda, its interface, and its method
InterfaceMethodShape
1Predicate<String>testTakes one, returns a boolean
2UnaryOperator<String>applyTakes one, returns the same type
3Consumer<String>acceptTakes one, returns nothing
4Comparator<String>compareTakes two, returns an int
5Supplier<String>getTakes 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.