peek isn't guaranteed to run
Pipeline A can't change the size of a sized list, so since Java 9 count() returns 3 without running it. On Java 8 'peek A' lines would print.
Stream operations fall into clear groups: stateless intermediate operations (filter, map, flatMap), stateful ones that must remember or buffer elements (distinct, sorted, limit), short-circuiting ones that can stop early (limit, anyMatch, findFirst), and terminal operations like reduce, min and toArray. Knowing which is which tells you what a pipeline costs and whether it can finish.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given sentences "the cat sat", "the dog ran", print the distinct words in alphabetical order using flatMap.
From List.of(3, 8, 12, 5, 20, 7), print the first two numbers greater than 6, and then the sum of all numbers using reduce with an identity.
Print the first 5 multiples of 7 that are also odd, starting from an infinite IntStream.iterate(7, n -> n + 7).
Explain it without notes
What is the difference between stateless and stateful intermediate operations? Give examples and explain why it matters.
Which operations are short-circuiting, and why do they matter for infinite streams?
Explain map versus flatMap, and when you'd use mapMulti.
What are the rules for the identity and accumulator in reduce, and what happens if you break them?
Why might a side effect inside peek or map not run?
Expected output
count A = 3
peek B 2
peek B 3
count B = 2