00:00

Lazy Evaluation in Java Streams

Last updated:

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 pipelineLazy?What happens when you call it
Stream source (list.stream(), Stream.of())YesCreates a description of the source; reads nothing
Intermediate operations (filter, map, sorted, ...)YesAdds a stage; runs nothing
Terminal operation (collect, count, forEach, ...)No (eager)Runs the pipeline and consumes the stream
iterator(), spliterator()PartlyTerminal, but hands out elements on demand
Arguments evaluated before the callNoNormal 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.

Building a pipeline compared with running it At build time, calling stream, filter and map only links stages; the lambdas run zero times. At run time, the terminal operation findFirst pulls the first element through filter and map, then the second, and stops at the first match, so the lambdas run only a few times. CALL WORK DONE LAMBDA CALLS orders.stream() build records the source 0 .filter(...) build adds a stage 0 .map(...) build adds a stage 0 .findFirst() run pulls until a match only as needed
Figure 1: Only the terminal call does any work, and it does only as much as the result needs.

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.

BuildThenRun.java
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());
    }
}
Output
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.

FirstPalindromeYear.java
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]);
    }
}
Output
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.

OnlyAsMuchAsNeeded.java
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());
    }
}
Output
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.

ArgumentsAreEager.java
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());
    }
}
Output
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() or anyMatch().
  • 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

AspectEager (loops, collections)Lazy (streams)
When work happensLine by line, immediatelyWhen the terminal operation runs
Intermediate resultsStored in temporary collectionsNot stored; elements flow through
Infinite sourcesImpossiblePossible with short-circuiting
Early exitbreakfindFirst(), limit(), anyMatch()
DebuggingStraightforwardLambdas 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

Wrong
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

Surprising
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 skip map() 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