Command Palette

Search for a command to run...

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

Stream sources, including infinite ones

The three-argument Stream.iterate and Stream.ofNullable arrived in Java 9; toList() in Java 16.

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?

Stream sources, including infinite ones Java 16+
Sign in to run this example in your browser.

Expected output

Stream.of:      [a, b, c]
Arrays.stream:  6
range(0, 5):    [0, 1, 2, 3, 4]
rangeClosed:    15
iterate+limit:  [1, 2, 4, 8, 16, 32]
iterate, 3 arg: [1, 3, 9, 27, 81]
generate+limit: [hi, hi, hi]
String.chars:   [1, 2, 3]
map entries:    rice, tea
ofNullable:     0
empty:          false