Sub topic 10
Why Streams Are Lazy
When you write a stream pipeline, the work does not happen line by line. Streams are lazy. Lazy means a step waits to run until a result is actually needed. This chapter shows what that means and why it helps.
Nothing Happens Without a Terminal Operation
A terminal operation is the last step in a pipeline, such as count, collect, or findFirst. It asks for a result. Intermediate operations like filter and map only describe the work. They do not run on their own.
Look at this pipeline with no terminal operation:
import java.util.stream.Stream;
public class NoTerminalExample {
public static void main(String[] args) {
Stream.of("a", "b", "c")
.filter(s -> {
System.out.println("filter " + s);
return true;
});
System.out.println("done");
// Prints only:
// done
}
}The filter lambda never prints. No terminal operation asked for elements, so the filter had nothing to do.
One Element at a Time
When a terminal operation runs, it pulls elements through the pipeline one at a time. The first element goes through every step before the second element starts. The stream does not filter the whole list first and then map the whole list.
Short-Circuiting
Some terminal operations can stop early. This is called short-circuiting: the stream stops once it has the answer. findFirst, anyMatch, and limit all work this way.
import java.util.stream.Stream;
public class LazyExample {
public static void main(String[] args) {
Stream.of("a", "b", "c")
.filter(s -> {
System.out.println("filter " + s);
return true;
})
.map(s -> {
System.out.println("map " + s);
return s.toUpperCase();
})
.findFirst();
// Prints only:
// filter a
// map a
}
}The element "a" passes the filter and gets mapped. findFirst now has its answer, so "b" and "c" are never touched.
Why Laziness Helps
| Benefit | What it means |
|---|---|
| Less work | Elements that are not needed are never processed. |
| No extra lists | Steps pass elements along directly. No in-between list is built. |
| Endless sources | A stream can describe an infinite sequence, because only the needed part is ever made. |
Exercise
The pipeline Stream.of(1, 2, 3, 4).filter(n -> n > 1).anyMatch(n -> n % 2 == 0) runs. How many elements does the filter check, and why?
Show answer
Two. The filter checks 1, which fails. It then checks 2, which passes, and anyMatch sees that 2 is even. anyMatch short-circuits and returns true, so 3 and 4 are never pulled.
Exercise
You write list.stream().map(s -> s.trim()); and nothing happens. What is missing?
Show answer
A terminal operation, such as collect or toList. Without one, the map step only describes the work and never runs.