Sub topic 10
Why Streams Are Lazy
When you write a stream pipeline, it looks as if each step runs right away, one after another. That is not what happens. Java streams are lazy: they do no work until the result is actually needed. This chapter covers what laziness means, how a stream moves elements through a pipeline, and why that saves time and memory.
What "lazy" means
Lazy evaluation means a calculation is put off until its result is needed. The opposite is eager evaluation, where a calculation runs as soon as you write it.
Recall the three parts of a pipeline from earlier chapters:
- A source supplies the elements, for example a list.
- Intermediate operations such as
filterandmapdescribe changes to the elements. Each one returns a new stream. - A terminal operation such as
collect,count, orfindFirstproduces the final result and ends the stream.
The rule is simple: intermediate operations do nothing on their own. They only record a plan. The terminal operation starts the work.
Seeing laziness in action
The program below builds a pipeline with a filter that prints a message every time it runs. Watch when the messages appear.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NoTerminalExample {
public static void main(String[] args) {
Stream<String> pipeline = Stream.of("a", "b", "c")
.filter(s -> {
System.out.println("filter " + s);
return true;
});
System.out.println("Pipeline built. Nothing has run yet.");
List<String> result = pipeline.collect(Collectors.toList());
System.out.println(result);
}
}Output:
Pipeline built. Nothing has run yet.
filter a
filter b
filter c
[a, b, c]The line Pipeline built. Nothing has run yet. prints first. The filter lambda did not run when you called filter. It ran only when collect, the terminal operation, asked for elements.
Elements travel one at a time
You might picture a stream doing all the filtering first, building a full temporary list, and then doing all the mapping. It does not work that way. A stream takes one element at a time through the whole pipeline before it moves on to the next element.
This program shows the order:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class OrderExample {
public static void main(String[] args) {
List<String> result = Stream.of("one", "two", "three", "four")
.filter(s -> {
System.out.println("filter " + s);
return s.length() > 3;
})
.map(s -> {
System.out.println("map " + s);
return s.toUpperCase();
})
.collect(Collectors.toList());
System.out.println(result);
}
}Output:
filter one
filter two
filter three
map three
filter four
map four
[THREE, FOUR]Notice two things:
"three"is filtered and then mapped right away, before"four"is even looked at."one"and"two"fail the filter, somapnever sees them. No work is wasted on elements that are thrown away.
Because of this, the stream never needs to store an in-between list. Each element passes through and is done.
You can think of the terminal operation as the one doing the pulling. It asks for the next element, and the request travels back up the pipeline to the source.
Short-circuiting: stopping early
Some operations can give their answer without looking at every element. These are called short-circuiting operations. Since streams are lazy, when such an operation has its answer, the stream simply stops. The remaining elements are never touched.
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
}
}findFirst needs only one element. As soon as "a" comes out of map, the job is finished. "b" and "c" are never filtered or mapped.
Here is another example with anyMatch, which answers "does at least one element match?":
import java.util.List;
public class AnyMatchExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 7, 12, 5, 20, 9);
boolean hasBig = numbers.stream()
.peek(n -> System.out.println("checking " + n))
.anyMatch(n -> n > 10);
System.out.println("Found one over 10: " + hasBig);
}
}Output:
checking 3
checking 7
checking 12
Found one over 10: truepeek is an intermediate operation that lets you look at each element as it passes. It is mainly used for debugging like this. The stream stops at 12, so 5, 20, and 9 are never checked.
The table lists the common short-circuiting operations.
| Operation | Kind | Stops when |
|---|---|---|
| `findFirst()` | Terminal | It finds the first element |
| `findAny()` | Terminal | It finds any element |
| `anyMatch(p)` | Terminal | An element matches `p` |
| `allMatch(p)` | Terminal | An element fails `p` |
| `noneMatch(p)` | Terminal | An element matches `p` |
| `limit(n)` | Intermediate | It has passed `n` elements |
Operations such as collect, count, forEach, and reduce are not short-circuiting. They need every element.
Why laziness matters
Laziness gives you three practical benefits.
- Less work. Elements that are filtered out skip the later steps. Short-circuiting operations skip the rest of the stream entirely.
- Less memory. The stream does not build a temporary collection between steps.
- Endless sources become possible. A stream can describe an endless sequence, because it only produces the elements that are asked for. With
limit, you take just the part you need. A later chapter on infinite streams covers this in detail.
Things to watch for
Laziness has a few effects that can surprise you.
- Order of operations matters for speed. Put
filterbefore an expensivemapso that the costly work runs only on the elements you keep. - Debug prints may not appear. If you add
peekor a print inside a lambda and see no output, check that the pipeline has a terminal operation, and check whether it stopped early. - Some operations must see everything first.
sortedcannot hand out its first element until it has read the whole stream, because the smallest element could come last. It still waits for a terminal operation, but it breaks the one-at-a-time flow for the steps before it.
Exercises
Exercise
A pipeline is written as list.stream().filter(s -> s.isEmpty()).map(String::trim); with no further calls. How many times does the filter lambda run?
Show answer
Zero times. filter and map are intermediate operations that only record the plan. Without a terminal operation such as collect or count, no element is ever pulled through the pipeline.
Exercise
For Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).map(n -> n * 10).findFirst(), list in order every filter and map call that happens.
Show answer
filter 1 (rejected), filter 2 (accepted), map 2 (gives 20). Then findFirst has its answer and the stream stops, so 3 and 4 are never filtered.
Exercise
You have a stream of 1,000 file names and want the first one ending in ".txt", converted with an expensive method loadTitle. Should you write filter then map, or map then filter? Why?
Show answer
Write filter(name -> name.endsWith(".txt")) first, then map(this::loadTitle), then findFirst(). Each element goes through the whole pipeline before the next one starts, so only the names that pass the filter reach loadTitle. findFirst also stops after the first match, so loadTitle runs once at most.