Card 08/ 09
All 9 cards
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.
// 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 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.