Sub topic 3
Anatomy of a Stream Pipeline
A stream does nothing useful on its own. You have to build a pipeline around it. A pipeline is a chain of steps that data flows through, one step after another. This chapter covers the three parts every pipeline has, how they connect, and what each part gives back.
The three parts of every pipeline
Every stream pipeline has the same shape:
- A source. The source is where the elements come from, such as a
List. You turn it into a stream, usually by calling.stream(). - Zero or more intermediate operations. An intermediate operation is a step that takes a stream and gives back a new stream. Examples are
filterandmap. - Exactly one terminal operation. A terminal operation is the last step. It ends the pipeline and produces a result, such as a list, a number, or printed output. Examples are
collect,count, andforEach.
Here is the flow as a picture.
An assembly line is a good way to picture this. The source puts raw items on the belt. Each intermediate operation is a worker who checks or changes items as they pass. The terminal operation is the packing station at the end that boxes up the finished product.
A pipeline, piece by piece
Most real code writes a pipeline as one long chain. Splitting it into separate variables makes each part easier to see. The program below does that, and it writes the type of every step out in full.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PipelineParts {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
// 1. Source: turn the list into a stream
Stream<String> source = names.stream();
// 2. Intermediate operations: each returns a new Stream
Stream<String> longNames = source.filter(name -> name.length() > 3);
Stream<String> upperNames = longNames.map(String::toUpperCase);
// 3. Terminal operation: produces a result that is not a Stream
List<String> result = upperNames.collect(Collectors.toList());
System.out.println(result); // [ALICE, CAROL, DAVE]
System.out.println(names); // [alice, bob, carol, dave]
}
}Look at the types:
names.stream()returns aStream<String>.filter(...)returns aStream<String>.map(...)returns aStream<String>.collect(...)returns aList<String>. That is not a stream, so the pipeline ends here.
The last line also prints the original list, and it has not changed. A stream reads from its source and never modifies it. The results go into a new list.
The usual chained style does exactly the same thing:
import java.util.List;
import java.util.stream.Collectors;
public class FilterMapExample {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result); // [ALICE, CAROL, DAVE]
}
}Chaining works because every intermediate operation returns a stream, so you can call the next method directly on it. Putting one operation on each line keeps the pipeline easy to read.
How to tell the parts apart
Look at the return type to tell an intermediate operation from a terminal one. If a method returns a Stream, it is intermediate. If it returns anything else, it is terminal.
| Part | What it does | What it returns | Examples |
|---|---|---|---|
| Source | Supplies the elements | A `Stream` | `list.stream()`, `Stream.of(...)` |
| Intermediate operation | Selects, changes, or reorders elements | A new `Stream` | `filter`, `map`, `sorted`, `distinct`, `limit` |
| Terminal operation | Ends the pipeline and makes a result | A value, a collection, or nothing (`void`) | `collect`, `count`, `forEach`, `findFirst` |
How many of each a pipeline has:
- Source: exactly one.
- Intermediate operations: zero or more. A pipeline with none is fine, for example
names.stream().count(). - Terminal operation: exactly one, and it always comes last.
The element type can change along the way
Every step in a pipeline has an element type. Some operations change it. The map operation is the most common one that does. In this example, the stream starts with strings and ends with whole numbers.
import java.util.List;
public class TypeChange {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
long count = names.stream() // Stream<String>
.map(String::length) // Stream<Integer>
.filter(len -> len > 3) // Stream<Integer>
.count(); // long
System.out.println(count); // 3
}
}After map(String::length), each element is the length of a name: 5, 3, 5, 4. The filter keeps lengths greater than 3, so 5, 5, and 4 remain. The terminal operation count returns a long with the value 3.
This is why order matters. Each step can only use what the previous step handed it. After the map, the names are gone and only numbers remain. You could not filter by "starts with a" at that point, because the elements are no longer strings.
No terminal operation, no work
Intermediate operations do not run when you call them. They only describe what should happen later. The work starts when a terminal operation asks for results. If you leave the terminal operation out, nothing happens:
import java.util.List;
public class NoTerminal {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob");
names.stream()
.map(name -> {
System.out.println("Mapping " + name);
return name.toUpperCase();
});
System.out.println("Done");
}
}This program prints only Done. The "Mapping" messages never appear, because no terminal operation pulled any elements through the map. This behavior is called lazy evaluation, and a later chapter covers it in detail. For now, remember one rule: a pipeline needs a terminal operation, or none of its steps run.
One pipeline, one trip
After a terminal operation runs, the stream is consumed. Consumed means used up: you cannot attach another terminal operation to the same stream object. If you want a second result, start a new pipeline from the source by calling names.stream() again. A later chapter on common mistakes shows the error you get if you try to reuse a stream.
Reading a pipeline out loud
You can read a pipeline as a sentence, which helps you check that it says what you mean. Here is the FilterMapExample again:
names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());Read it like this: "Take the names, keep those longer than three characters, convert each to upper case, and collect the results into a list." Each line corresponds to one part of the sentence. If the sentence sounds wrong, the code probably is wrong too.
Exercise
In the pipeline words.stream().filter(w -> w.startsWith("a")).map(String::length).count(), name the source, each intermediate operation, and the terminal operation. What is the element type after each step, and what type does the whole expression return? Assume words is a List<String>.
Show answer
The source is words.stream(), which gives a Stream<String>. The first intermediate operation is filter, which still gives a Stream<String>. The second is map(String::length), which gives a Stream<Integer>. The terminal operation is count(), so the whole expression returns a long.
Exercise
A teammate writes List.of(1, 2, 3).stream().map(n -> { System.out.println(n); return n * 2; }); and says nothing is printed. Why, and what is the smallest change that makes the numbers print?
Show answer
The pipeline has no terminal operation, so the map step never runs. Add a terminal operation at the end, for example .count() or .collect(Collectors.toList()). A terminal operation pulls the elements through the map, so 1, 2, and 3 are printed. (On Java 9 and later, count() may skip running map when it can work out the size directly from the source. A terminal operation that needs the values, such as collect or forEach, always prints them.)
Exercise
Why does names.stream().map(String::length).filter(n -> n.startsWith("a")) fail to compile?
Show answer
After map(String::length), the stream holds Integer values, not String values. Integer has no startsWith method. To filter by the first letter, put the filter before the map, while the elements are still strings.