Command Palette

Search for a command to run...

Back to the lesson: Topic 10.4 — Streams: The Basics
Core Java · Example 5 of 5 Java 16+

A stream is used once; the source can be streamed again

A pipeline is a straight line, not a tree. Chaining map onto base used base up, so a second branch from it is refused.

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.

01

From List.of("tea", "coffee", "juice", "milk"), print a list of the words with more than 3 letters, upper-cased, using a stream.

02

Print the sum of squares of the odd numbers from 1 to 9 with a single IntStream pipeline.

03

Use Stream.iterate with three arguments to print the powers of 2 below 1000 as a list.

Explain it without notes

01

What is a stream, and how is it different from a collection?

02

Explain laziness in streams. What actually happens when you call filter and when you call toList?

03

Why can a stream be used only once?

04

Why do primitive streams exist, and how do you move between Stream<T> and IntStream?

A stream is used once; the source can be streamed again Java 16+
Sign in to run this example in your browser.

Expected output

count: 3
second use: stream has already been operated upon or closed
fresh stream: 3
branching: stream has already been operated upon or closed
[X, Y, Z]