Card 08/ 09

ExerciseDifficulty: Advanced1 min

Five Lambdas: Name the Interface Each One Implements

Five lambdas in context. For each, name the functional interface it lands in and the method it supplies. All five before the reveal.

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 has a bug in it as well as an interface: subtracting two int values in a comparator can overflow. Comparator.comparingInt(String::length) is the version that cannot.