Card 09/ 10
All 10 cards
ExerciseDifficulty: Advanced1 min
Four Pipelines: Write Down What Comes Out of Each
Four pipelines over the same five words. Write down the output of each, or that nothing happens, before opening the reveal.
List<String> words = List.of("pear", "fig", "apple", "fig", "plum");
// 1
words.stream().filter(w -> w.length() > 3).map(String::toUpperCase);
// 2
words.stream().distinct().count();
// 3
words.stream().map(w -> w.split("")).toList();
// 4
words.stream().flatMap(w -> Arrays.stream(w.split(""))).distinct().sorted().limit(3).toList();What each of the four produces
| Result | Why | |
|---|---|---|
| 1 | Nothing happens at all | No terminal operation, so the description is built and discarded |
| 2 | 4 | distinct removes the second fig before count runs |
| 3 | A list of five arrays | map returns one value per element, and that value is an array |
| 4 | [a, e, f] | flatMap flattens the letters, then distinct, then sorted, then the first three |
The third is the one that produces a type nobody wanted. A List<String[]> in the middle of a pipeline is the signature of a map that should have been a flatMap.
The fourth is worth tracing for the laziness: limit(3) means sorted still has to see everything — sorting cannot produce its first element until it has them all — while a limit before a sorted would not.