Lazy Evaluation in Java Streams
Lazy evaluation in the Java Stream API (Java 8+) means that intermediate operations such as filter() and map() do not process any data when they are called. They only record a step in the pipeline. The work happens when a terminal operation is invoked, and even then only for as many elements as the result requires.
Laziness is what lets streams handle infinite sources, avoid unnecessary computation and fuse several steps into a single pass. This tutorial shows laziness at work, explains what is and is not lazy, and points out the bugs that come from forgetting it.
1. What Is Lazy and What Is Not
| Part of a pipeline | Lazy? | What happens when you call it |
|---|---|---|
Stream source (list.stream(), Stream.of()) | Yes | Creates a description of the source; reads nothing |
Intermediate operations (filter, map, sorted, ...) | Yes | Adds a stage; runs nothing |
Terminal operation (collect, count, forEach, ...) | No (eager) | Runs the pipeline and consumes the stream |
iterator(), spliterator() | Partly | Terminal, but hands out elements on demand |
| Arguments evaluated before the call | No | Normal Java rules: Stream.of(compute()) calls compute() immediately |
2. How Lazy Evaluation Works
Each intermediate call returns a new stream object that remembers its operation and the previous stage. When a terminal operation runs, the library connects the stages into a chain of consumers and asks the source for elements one at a time. Each element flows through the entire chain before the next is read (vertical processing), so a short-circuiting terminal operation can stop after the first useful element.
Laziness also allows loop fusion: filter().map().filter() runs as one loop, not three. And it gives the library freedom to skip work, for example not running map() when count() can use the known size.
3. Java Examples
Example 1: Nothing runs until the terminal operation (Java 16+)
Build a pipeline with logging lambdas, print a message, then run it.
import java.util.List;
import java.util.stream.Stream;
public class BuildThenRun {
public static void main(String[] args) {
List<String> cities = List.of("Pune", "Kolkata", "Agra");
Stream<String> pipeline = cities.stream()
.filter(c -> {
System.out.println(" filter " + c);
return c.length() > 4;
})
.map(c -> {
System.out.println(" map " + c);
return c.toUpperCase();
});
System.out.println("Pipeline built");
System.out.println("Result: " + pipeline.toList());
}
}
Pipeline built filter Pune filter Kolkata map Kolkata filter Agra Result: [KOLKATA]
How it works: "Pipeline built" is printed first: creating the stream and adding stages did nothing. The lambdas run only inside toList(), one element at a time.
Example 2: Laziness makes infinite sources usable
Find the next palindrome year after 2026 (a year that reads the same backwards), using an endless stream of years.
import java.util.stream.IntStream;
public class FirstPalindromeYear {
static boolean isPalindrome(int n) {
String s = String.valueOf(n);
return new StringBuilder(s).reverse().toString().equals(s);
}
public static void main(String[] args) {
int[] examined = {0};
int year = IntStream.iterate(2027, y -> y + 1)
.peek(y -> examined[0]++)
.filter(FirstPalindromeYear::isPalindrome)
.findFirst()
.getAsInt();
System.out.println("Next palindrome year: " + year);
System.out.println("Years examined: " + examined[0]);
}
}
Next palindrome year: 2112 Years examined: 86
How it works: The source is infinite, but laziness and findFirst() stop it after 86 years. An eager approach would have to build the infinite list first.
Example 3: Expensive work only where needed (Java 16+)
Price-check products against a slow pricing service, but only until three affordable ones are found.
import java.util.List;
public class OnlyAsMuchAsNeeded {
static int calls = 0;
static int slowPrice(String sku) {
calls++;
return sku.length() * 150; // stands in for a remote call
}
public static void main(String[] args) {
List<String> skus = List.of("PEN", "LAPTOP", "INK", "MONITOR", "CLIP", "TABLET", "PAD", "GLUE");
List<String> affordable = skus.stream()
.filter(sku -> slowPrice(sku) <= 600)
.limit(3)
.toList();
System.out.println("Affordable: " + affordable);
System.out.println("Pricing calls: " + calls + " of " + skus.size());
}
}
Affordable: [PEN, INK, CLIP] Pricing calls: 5 of 8
How it works: limit(3) stops the pipeline as soon as three products pass, so the last three SKUs are never priced. With a loop you would write this break yourself.
Example 4: Arguments are not lazy (Java 10+)
Show that values passed to Stream.of() are computed before the stream exists.
import java.util.function.Supplier;
import java.util.stream.Stream;
public class ArgumentsAreEager {
static String load(String name) {
System.out.println(" loading " + name);
return name.toUpperCase();
}
public static void main(String[] args) {
System.out.println("Stream.of with direct calls:");
String first = Stream.of(load("a"), load("b"), load("c")).findFirst().orElseThrow();
System.out.println(" first = " + first);
System.out.println("Stream of suppliers:");
Stream<Supplier<String>> lazy = Stream.of(() -> load("a"), () -> load("b"), () -> load("c"));
System.out.println(" first = " + lazy.map(Supplier::get).findFirst().orElseThrow());
}
}
Stream.of with direct calls: loading a loading b loading c first = A Stream of suppliers: loading a first = A
How it works: Java evaluates method arguments before calling the method, so all three loads run. Wrapping each load in a Supplier and calling it in map() moves the work into the lazy pipeline, and only one load runs.
4. Real-World Use Cases
- Large files:
Files.lines()reads only the lines the pipeline needs. - Expensive lookups: calls to slow services happen only for elements that reach them.
- Search: stop at the first matching record with
findFirst()oranyMatch(). - Generated data: infinite sequences of ids, dates or test cases.
5. Important Points
- No terminal operation, no work.
- Side effects run late, in a different order than the code suggests, or not at all.
- Stateful operations such as
sorted()must read everything before passing anything on, which limits laziness. - The source is read when the terminal operation runs, so changes to a collection made before that point are visible.
- Exceptions in lambdas surface only during the terminal operation.
6. Eager vs Lazy Processing
| Aspect | Eager (loops, collections) | Lazy (streams) |
|---|---|---|
| When work happens | Line by line, immediately | When the terminal operation runs |
| Intermediate results | Stored in temporary collections | Not stored; elements flow through |
| Infinite sources | Impossible | Possible with short-circuiting |
| Early exit | break | findFirst(), limit(), anyMatch() |
| Debugging | Straightforward | Lambdas run later; use peek() carefully |
See Short-Circuit Operations for the operations that make early exit possible.
7. Common Mistakes and Best Practices
Expecting work without a terminal operation
invoices.stream().map(this::sendReminder); // nothing is sent
Relying on the timing of side effects
Lambdas run during the terminal operation, interleaved element by element, and some may be skipped. Never depend on when, how often or in which order a lambda's side effect happens.
Holding a stream for later
Stream<Order> pending = orders.stream().filter(Order::isPending);
orders.add(newOrder); // will be included: the source is read later
long n = pending.count();
Create the stream right before the terminal operation, or collect the result immediately.
Other mistakes to avoid
- Expecting
Stream.of(expensive())to be lazy. - Putting a short-circuit after
sorted()and expecting it to avoid reading everything. - Forgetting that
count()may skipmap()on sized streams.
8. Summary
- Intermediate operations are lazy; the terminal operation runs the pipeline.
- Elements flow one at a time through all stages, so work stops as soon as the result is known.
- Laziness enables infinite sources, loop fusion and skipped work.
- Do not rely on the timing or count of side effects in lambdas.
9. References
Frequently Asked Questions (FAQ)
Q1. What is lazy evaluation in Java streams?
Intermediate operations only describe the work and do not process data when they are called. The pipeline runs when a terminal operation is invoked, and only as far as needed to produce the result.
Q2. Why are Java streams lazy?
Laziness allows infinite sources, short-circuiting, single-pass execution of several steps (loop fusion), and optimisations such as skipping work that cannot change the result.
Q3. Are all stream operations lazy?
Intermediate operations are lazy. Terminal operations are eager: they trigger processing. Stateful intermediate operations such as sorted() must still read all elements before passing any on.
Q4. Why does my map() not run?
Either the pipeline has no terminal operation, or the terminal operation does not need it, for example count() on a stream whose size is known, which since Java 9 may skip map().
Q5. Is the source collection read when stream() is called?
No. For most JDK collections the source is bound when the terminal operation starts, so changes made before that are visible to the stream.