Laziness and vertical processing, made visible
Each name goes through filter and map before the next name starts. findFirst stops after the first survivor, so bo, meera and kabir are never even filtered.
A stream is a pipeline that pulls elements from a source, passes them through intermediate operations like filter and map, and produces a result with one terminal operation. Streams are lazy (nothing runs until the terminal operation), can be used only once, and never change their source.
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.
From List.of("tea", "coffee", "juice", "milk"), print a list of the words with more than 3 letters, upper-cased, using a stream.
Print the sum of squares of the odd numbers from 1 to 9 with a single IntStream pipeline.
Use Stream.iterate with three arguments to print the powers of 2 below 1000 as a list.
Explain it without notes
What is a stream, and how is it different from a collection?
Explain laziness in streams. What actually happens when you call filter and when you call toList?
Why can a stream be used only once?
Why do primitive streams exist, and how do you move between Stream<T> and IntStream?
Expected output
pipeline built, nothing has run yet
filter asha
map asha
filter bo
filter meera
map meera
filter kabir
map kabir
result: [ASHA, MEERA, KABIR]
with findFirst:
filter asha
map asha
first: ASHA