The same query as a loop and as a stream
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
loop: [ASHA, MEERA, KABIR]
stream: [ASHA, MEERA, KABIR]
total paid: 3940
source untouched: 5 orders