The stream pipeline
Most collection work is the same three verbs in different orders: keep some elements, transform them, gather a result. Written as loops, the verbs smear across mutable helper variables; written as a stream, each verb is one named stage, and a reviewer reads the intent line by line. Streams are the house style for this in modern Java codebases, so you will read them daily even before you write them. A stream processes a collection in stages, each stage taking a lambda. It is Java's answer to Python's list comprehensions:
[n * n for n in nums if n % 2 == 0]
nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList());
stream()opens the pipeline.filter(predicate)keeps elements that pass the test.map(function)transforms each element.- A terminal operation ends the pipeline and produces the result:
collect(Collectors.toList())builds a list,count()counts,mapToInt(...).sum()totals.
Nothing runs until the terminal operation, and the source collection is never modified.
Code exercise · java
Run the pipeline. Note the two imports, and that the original nums list is untouched afterward.
More stages and endings
A few more pieces cover most day-to-day pipelines. Mid-pipeline stages: distinct() drops duplicates, sorted() orders elements, limit(n) keeps the first n. Terminal operations besides collect:
| Terminal | Produces |
|---|---|
count() | how many elements survived, as a long |
anyMatch(predicate) | true as soon as one element passes |
mapToInt(n -> n).sum() | a total (int math needs the mapToInt bridge) |
toList() | a List — modern shorthand for collect(Collectors.toList()) |
One rule to keep pipelines honest: a stream never modifies its source, and each stream can be consumed by exactly one terminal operation — build a fresh stream() for each question you ask.
Code exercise · java
Run this. Four questions about one list, each as its own small pipeline: a count, a cleaned-and-sorted copy, a yes/no, and a sum. The source list is never modified.
Quiz
Which line of a stream pipeline actually triggers the work?
Code exercise · java
Your turn. From the words list, build a list of the words with length at most 4, uppercased, and print it. Then count the words longer than 4 characters and print the count.