Stream pipeline and laziness
What you will learn
A Java stream describes a sequence of operations over data. Unlike a list, it is not a container you index or update. Build a pipeline from a source, add transformations, then request a result. The terminal operation determines when processing starts.
- Distinguish source, intermediate and terminal operations.
- Predict ordered slicing and short-circuit results.
- Create a fresh stream for each traversal.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
From stock list to selected quantities
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { List<Integer> stock = List.of(0, 4, 2, 0, 7); var available = stock.stream().filter(n -> n > 0); System.out.println(available.toList()); System.out.println(stock); }}Expected output:
[4, 2, 7][0, 4, 2, 0, 7]The pipeline selects positive quantities without removing anything from the source.
Read a pipeline from source to result
A collection owns or exposes elements; a stream carries them through a computation. list.stream() and Arrays.stream(array) create sources; Stream.of(...) is useful for literal fixtures. Intermediate operations such as filter and map describe work and return another stream. A terminal operation such as toList, count or findFirst requests a result. Intermediate operations do not start traversal on their own. Avoid mutating the source during traversal. A stream does not automatically snapshot a mutable collection.
Order, bounds and reuse
Encounter order is the source-defined or pipeline-imposed sequence, not necessarily sorted order. List streams are ordered; HashSet streams do not promise an encounter order. distinct() removes equal duplicates; sorted() imposes order. skip(n) drops the first n elements of an ordered stream; limit(n) keeps at most n. takeWhile and dropWhile operate on a matching prefix in ordered streams, not all matching elements. Both were added in Java 9. findFirst returns an Optional: use orElse to specify a fallback for an empty result (Chapter 22 covers Optional in depth). A pipeline is single-use; create a new stream rather than reusing a consumed one. Java may detect reuse and throw IllegalStateException, but detection is not guaranteed in every case.
Termination and resources
Bound an otherwise unbounded generator before collecting; sorting an infinite stream before applying a limit can prevent completion. Short-circuit operations may finish without visiting all values. Do not rely on exact callback counts or use peek for required work. Most collection streams need no explicit close, but streams from resources such as Files.lines must be closed with try-with-resources. Stream.toList (Java 16+) returns an unmodifiable list; it does not freeze its elements.
Sort and slice a report
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var result = Stream.of(9, 3, 5, 3, 1).distinct().sorted().skip(1).limit(2).toList(); System.out.println(result); }}Expected output:
[3, 5]Sorting the unique numbers gives 1, 3, 5, 9; skipping one and taking two yields 3 and 5.
Prefix rules versus filtering
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var values = List.of(2, 4, 7, 6); System.out.println(values.stream().takeWhile(n -> n % 2 == 0).toList()); System.out.println(values.stream().dropWhile(n -> n % 2 == 0).toList()); System.out.println(values.stream().filter(n -> n % 2 == 0).toList()); }}Expected output:
[2, 4][7, 6][2, 4, 6]The value 7 ends the matching prefix. Filtering still considers the later 6.
Bound a generated sequence
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { System.out.println(Stream.iterate(10, n -> n + 10).limit(4).toList()); System.out.println(Stream.<String>empty().findFirst().orElse("missing")); }}Expected output:
[10, 20, 30, 40]missingThe limit bounds an infinite source; the empty search has an explicit fallback.
Common mistakes
Do not store one Stream and call two terminal operations on it. Store the source collection or a stream factory instead. A second traversal should build a new pipeline. Avoid using peek to increment a business counter: an implementation may skip stages that cannot change the result.
Practice
Given [8, 2, 8, 1, 5, 3], remove duplicates, sort descending, skip the largest value and return the next three. Print the result and the unchanged original list.
Expected output:
[5, 3, 2][8, 2, 8, 1, 5, 3]Compare your answer with the manual practice criteria.
Official reading: Java SE 25 Stream API · Stream package contracts · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stream pipeline and laziness — knowledge check
Original Java stream contract and boundary questions. Java 21-compatible scope.
Which operation requests a final list?
What does takeWhile(even) return for [2, 3, 4]?
How should you traverse a list twice?
What can happen to a peek callback in a count pipeline?
What is the result of sorted().limit(2) on [9, 1, 4]?