ExerciseDifficulty: Advanced1 min

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.

java
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
Each pipeline, its result, and why
ResultWhy
1Nothing happens at allNo terminal operation, so the description is built and discarded
24distinct removes the second fig before count runs
3A list of five arraysmap 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.