Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
Stream pipelines for the OCP 21 exam: source, intermediate and terminal operations, lazy evaluation and single use, creating streams with Stream.of, ofNullable, collection.stream, Arrays.stream, generate and both forms of iterate, plus parallel streams and the late-binding source.
kvi5hnuCode Sprout team member7 min readOn this page
A stream (java.util.stream.Stream<T>) is a sequence of elements that you process with a chain of operations, describing what to do rather than writing the loop yourself:
long longWords = words.stream()
.filter(w -> w.length() > 5)
.count();
These streams have nothing to do with java.io input/output streams (chapter 14). The shared name is a coincidence.
The pipeline

A stream pipeline has three parts:
- Source: where the elements come from, such as a collection, an array, explicit values or a generator.
- Intermediate operations: zero or more steps that each return a new stream, such as
filter,map,sortedandlimit. - Terminal operation: exactly one step that produces a result (or a side effect) and ends the pipeline, such as
count,forEach,collectorfindFirst.
Think of an assembly line. Nothing moves until someone presses "start", and that's the terminal operation. Then each item travels down the line, and the line stops as soon as the job is done.
| Intermediate operation | Terminal operation | |
|---|---|---|
| Needed for a useful pipeline? | no | yes |
| How many per pipeline? | any number | exactly one |
| Returns a stream? | yes | no |
| Runs when called? | no: lazy | yes, and it triggers the intermediate steps |
| Stream usable afterwards? | the new stream, yes | no |
Lazy evaluation
Intermediate operations only describe work. Without a terminal operation, nothing runs:
Stream.of("a", "b").map(s -> { System.out.println("never"); return s; }); // prints nothing
When the terminal operation runs, elements go through the pipeline one at a time. The first element passes through every step before the second one starts. Stateful steps such as sorted() are the exception, because they must see every element first. Combined with short-circuiting operations, this means a stream may not even read all of its source:
Stream.of("plum", "fig", "pear", "kiwi")
.filter(s -> s.length() == 4) // runs only for "plum"
.map(String::toUpperCase) // runs only for "plum"
.findFirst(); // stops after the first match
Single use
A stream can be traversed once. After a terminal operation, or after you've chained another operation onto it, the stream object is consumed. Using it again throws IllegalStateException: "stream has already been operated upon or closed".
Stream<String> s = Stream.of("x", "y");
s.count();
s.count(); // IllegalStateException
Stream<String> t = Stream.of("x");
Stream<String> u = t.filter(v -> true);
t.map(v -> v); // IllegalStateException: t was already used to create u
To process the same data twice, create a new stream from the source each time, or use a Supplier<Stream<T>>.
The source is read late
A stream from a collection doesn't copy the elements when you call stream(). It reads them when the terminal operation runs:
List<String> names = new ArrayList<>(List.of("ann", "bo"));
Stream<String> s = names.stream();
names.add("cy");
System.out.println(s.count()); // 3
Changing the collection while the pipeline is running, for example from inside forEach, isn't allowed. With an ArrayList, it throws ConcurrentModificationException.
Creating finite streams
| Source | Notes |
|---|---|
Stream.empty() | zero elements |
Stream.of(T... values) | the listed values. Stream.of(x) has exactly one element |
Stream.ofNullable(T t) (Java 9) | one element, or zero if t is null |
collection.stream() | elements of any Collection, in its iteration order |
collection.parallelStream() | the same, but it may be processed in parallel |
Arrays.stream(array) / Arrays.stream(array, from, to) | an array, or part of one (to is exclusive) |
Stream.concat(a, b) | all of a, then all of b |
Stream.builder().add(x).add(y).build() | build element by element |
Other APIs return streams too: String.chars(), String.lines() (Java 11), Map.entrySet().stream(), and Files.lines(path) (chapter 14). A Map itself has no stream() method. Stream over one of its views instead.
Stream<String> fromSet = new TreeSet<>(Set.of("fir", "yew")).stream(); // fir, yew
Stream<String> slice = Arrays.stream(new String[] {"a", "b", "c", "d"}, 1, 3); // b, c
Stream<String> maybe = Stream.ofNullable(map.get("missing")); // 0 elements
Stream is an interface, so new Stream<>() doesn't compile. Type arguments must be reference types, so Stream<int> doesn't compile either; primitives have IntStream and friends (article 64). There's one subtle overload: Stream.of(new int[]{1, 2}) is a stream of one element, the array itself, because int[] can't be spread into T.... Stream.of(new Integer[]{1, 2}) has two elements.
Creating infinite streams
| Source | Elements |
|---|---|
Stream.generate(Supplier<T> s) | s.get(), s.get(), …, forever |
Stream.iterate(T seed, UnaryOperator<T> next) | seed, next(seed), next(next(seed)), … forever |
Stream.iterate(T seed, Predicate<T> hasNext, UnaryOperator<T> next) (Java 9) | like a for loop: stops as soon as hasNext is false. Finite or infinite, depending on the predicate |
Stream<Double> randoms = Stream.generate(Math::random);
Stream<Integer> odds = Stream.iterate(1, n -> n + 2); // 1, 3, 5, ...
Stream<Integer> under50 = Stream.iterate(1, n -> n < 50, n -> n * 3); // 1, 3, 9, 27
Exam details:
- The three-argument
iteratetakes seed, predicate, next, separated by commas. Semicolons, as in aforloop, don't compile, and neither does the wrong order (iterate(1, n -> n + 1, n -> n < 10)). generatetakes aSupplier, which has no parameter.Stream.generate(x -> Math.random())doesn't compile.- An infinite stream is fine as long as something stops it:
limit(n),takeWhile, or a short-circuiting terminal operation such asfindFirst,anyMatchorfindAny. Terminal operations that need every element (count,forEach,collect,reduce,min,max,allMatchwhen everything matches) never finish on an infinite stream. The program hangs. It doesn't throw an exception.
Stream.iterate(1, n -> n + 1).filter(n -> n > 100 && n % 7 == 0).findFirst(); // Optional[105]
Stream.generate(() -> "chimp").count(); // runs forever
Parallel streams
parallelStream() on a collection, or .parallel() on any stream, lets the pipeline split the work across several threads. isParallel() tells you which kind you have. Results that don't depend on order, such as sum and count, come out the same. Others, such as forEach output order and findAny, may differ. Parallel streams belong to chapter 13. For now, just know that they exist and use the same API.
Printing a stream
System.out.println(stream) prints an object reference such as java.util.stream.ReferencePipeline$Head@1b6d3586, not the elements. To see the elements, use a terminal operation: stream.toList(), forEach(System.out::println), or collect(Collectors.joining(", ")).
What's current
- Stream creation methods are unchanged through Java 25.
Stream.iteratewith a predicate (Java 9) andStream.ofNullable(Java 9) are current. - Java 24 finalized stream gatherers (
Stream.gather, JEP 485). They aren't on 1Z0-830.
Exam traps from this article
A complete example
The program creates streams from every common source, then makes two infinite streams finite. It prints from inside filter and map to show laziness and element-by-element processing, finds a value in an infinite stream, triggers the single-use exception, and shows the late-binding source.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) {
// 1. Finite sources
Stream<String> none = Stream.empty();
Stream<String> one = Stream.of("kayak");
Stream<String> several = Stream.of("oak", "ash", "elm");
Stream<String> maybe = Stream.ofNullable(null); // 0 elements instead of a NullPointerException
Set<String> trees = new TreeSet<>(Set.of("fir", "yew"));
Stream<String> fromSet = trees.stream();
Stream<String> fromArray = Arrays.stream(new String[] {"a", "b", "c", "d"}, 1, 3);
System.out.println("counts: " + none.count() + " " + one.count() + " " + several.count() + " "
+ maybe.count() + " " + fromSet.count() + " " + fromArray.count());
// 2. Infinite sources need something that stops them
List<Integer> powers = Stream.iterate(1, n -> n * 2).limit(6).toList();
List<Integer> under50 = Stream.iterate(1, n -> n < 50, n -> n * 3).toList();
String dashes = Stream.generate(() -> "-").limit(8).collect(Collectors.joining());
System.out.println("iterate+limit " + powers + ", iterate with predicate " + under50 + ", generate " + dashes);
// 3. Lazy, one element at a time: watch the order of the messages
System.out.println("building pipeline...");
Stream<String> pipeline = Stream.of("plum", "fig", "pear", "kiwi")
.filter(s -> { System.out.println(" filter " + s); return s.length() == 4; })
.map(s -> { System.out.println(" map " + s); return s.toUpperCase(); });
System.out.println("nothing has run yet; now calling findFirst()");
System.out.println("result: " + pipeline.findFirst().orElse("none"));
// 4. Infinite source + short-circuiting terminal operation finishes
System.out.println("first multiple of 7 above 100: "
+ Stream.iterate(1, n -> n + 1).filter(n -> n > 100 && n % 7 == 0).findFirst().orElseThrow());
// 5. A stream can be used only once
Stream<String> once = Stream.of("x", "y");
System.out.println("first use: " + once.count());
try {
once.count();
} catch (IllegalStateException e) {
System.out.println("second use: IllegalStateException (" + e.getMessage() + ")");
}
// 6. The source is read when the terminal operation runs, not when stream() is called
List<String> queue = new ArrayList<>(List.of("ann", "bo"));
Stream<String> later = queue.stream();
queue.add("cy");
System.out.println("elements seen: " + later.toList());
// 7. A parallel stream from the same list gives the same sum
System.out.println("parallel? " + queue.parallelStream().isParallel()
+ ", sum of lengths: " + queue.parallelStream().mapToInt(String::length).sum());
}
}
Output:
counts: 0 1 3 0 2 2
iterate+limit [1, 2, 4, 8, 16, 32], iterate with predicate [1, 3, 9, 27], generate --------
building pipeline...
nothing has run yet; now calling findFirst()
filter plum
map plum
result: PLUM
first multiple of 7 above 100: 105
first use: 2
second use: IllegalStateException (stream has already been operated upon or closed)
elements seen: [ann, bo, cy]
parallel? true, sum of lengths: 7
Points to notice:
Stream.ofNullable(null)counted 0, and theArrays.streamslice counted 2 (indexes 1 and 2).- "nothing has run yet" printed before any
filterormapmessage: the operations ran only whenfindFirst()was called. - Only
plumwent throughfilterandmap.findFirststopped the pipeline after the first match, sofig,pearandkiwiwere never examined. - The infinite
iteratefinished becausefindFirstshort-circuits. cy, added afterstream()was called, still appeared in the result.
Common questions
Is a stream a data structure? No. It holds no elements of its own. It's a view of a source plus a recipe of operations, and the elements are pulled through on demand.
Should every loop become a stream?
No. Streams shine for filter–transform–collect work. A simple loop with early breaks or index arithmetic is often clearer. Both are valid Java.
Why does forEach exist on both Iterable and Stream?
Iterable.forEach loops over a collection directly. Stream.forEach is a terminal operation at the end of a pipeline. list.forEach(...) and list.stream().forEach(...) behave the same for a sequential list.
Summary
- A pipeline is a source, then zero or more lazy intermediate operations, then exactly one terminal operation that triggers processing.
- Elements are processed one at a time, and short-circuiting operations can stop early, which makes infinite streams usable.
- A stream is single-use. Reuse throws
IllegalStateException. - Finite sources:
Stream.empty,of,ofNullable,collection.stream/parallelStream,Arrays.stream,concatandbuilder. - Infinite sources:
Stream.generate(supplier)andStream.iterate(seed, next). The three-argumentiterate(seed, hasNext, next)stops when the predicate fails.
Practice quiz
Test yourself with the stream pipelines quiz: 10 exam-style questions with explanations.
Previous: Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
Next: Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
Related reading
- Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
- Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
- Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
- Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
- Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.