Card 09/ 10
Practice: Predicting What Four Stream Pipelines Produce
Four pipelines over the same five words; one of them does nothing at all.
A pipeline runs only when it ends in a terminal operation (the last step, which produces a result and makes the stream run), map gives one value per element, and flatMap merges several. Using those rules, write down what each of the four pipelines below produces, or that nothing happens, before opening the answer.
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 laziness. sorted has to see every letter before it can give up its first, so limit(3) after it saves nothing upstream; the same limit placed before sorted would stop early, and would also change the answer.
← → move through sections and cards