Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Java › Lambdas and streams

Lazy evaluation in streams

A stream does not run in the order in which it is written

Why it exists — When you process a collection with a for loop, you must string together filtering, transforming, and collecting by hand with temporary lists and if statements, so the code gets long and its intent is hard to see. The Stream API lets you write what to do as a chain of step names such as filter and map, and has the library take on the iteration that takes out elements one by one and runs them, so that when only the first values are needed, as with findFirst, it can stop there.

Where it's used today — It is commonly used where you process a collection, such as picking only the items that match a condition from a list and converting them to DTOs, getting the total of order amounts, and grouping members by grade (groupingBy). For logic that needs exception handling at each step or changes to outside variables, a for loop is easier to read, and for data in a database, filter it in the database with WHERE rather than fetching everything and filtering with a stream.

Intermediate operations such as filter and map do nothing at the moment they are called. They run only when the terminal operation is called. Even then, the stream does not finish one operation for all the elements before it starts the next. It sends the elements through to the end one at a time.

Checked against real execution · Checked by running 12 combinations on JDK 21

Concepts in this lab

Stream API
This API expresses filtering, transformation, and aggregation over data such as collections in a declarative way. You chain intermediate operations such as filter and map, and finish with a terminal operation such as collect or forEach. Intermediate operations do not run until the terminal operation is called (lazy evaluation), and a stream does not modify its source data and can be used only once.
Lazy evaluation
Why it exists — If a computation is done immediately, it produces values that end up unused, and every step must store its whole intermediate result. Lazy evaluation removes that waste by delaying the computation until the value is actually used.
Where it's used today — Optional's orElseGet runs the Supplier only when there is no value, and the Logger of java.util.logging, when given a Supplier, does not build the message string if logging at that level is turned off.
This approach delays a computation until its result is actually needed. The intermediate operations of a stream do not run as soon as they are called. They run only when the terminal operation is called, and each element passes through the pipeline one at a time. The stream can process only as much as it needs and then stop. Lazy fetching in JPA follows the same idea: associated data is queried when it is actually used.
Lambda expression
This is a syntax, introduced in Java 8, for writing a function with no name in a compact way. It has the form (parameters) -> body, and it is used as the implementation of a functional interface, which has only one abstract method. It lets you pass behavior (code) to another method as if it were a value.
Optional
This container class expresses in the type that a value may or may not be present. When a method returns it in place of null, the caller is guided to handle the case where there is no value. It is used mainly as a method return type.

Try these

Running with the default settings

  1. stream(), filter(), map() were called in order. These calls only link together "what to do". They do not take a single element out. No lambda expression has run yet.
  2. toList() was called. Execution starts now. The terminal operation pulls the elements through one at a time.
  3. filter(5): It is greater than 3, so it passes. It goes straight on to the next operation, map.
  4. map(5): The value is changed to 50 and collected into the result list.
  5. filter(2): It is not greater than 3, so it is dropped. This element does not go to map.
  6. filter(8): It is greater than 3, so it passes. It goes straight on to the next operation, map.
  7. map(8): The value is changed to 80 and collected into the result list.
  8. filter(1): It is not greater than 3, so it is dropped. This element does not go to map.
  9. filter(9): It is greater than 3, so it passes. It goes straight on to the next operation, map.
  10. map(9): The value is changed to 90 and collected into the result list.
  11. filter(4): It is greater than 3, so it passes. It goes straight on to the next operation, map.
  12. map(4): The value is changed to 40 and collected into the result list.
  13. Result: [50, 80, 90, 40]

Result of this run

Code

// Only the lines inside main are shown (class, main declaration, and imports omitted)
List.of(5, 2, 8, 1, 9, 4).stream()
    .filter(x -> x > 3)          // only values greater than 3
    .map(x -> x * 10)            // multiply by 10
    .toList();

Assumptions of this model

The execution order and the result of all 12 combinations were checked against the result of running the same pipeline on JDK 21 in our test run. This applies to a sequential stream, and in a parallel stream the order in which the elements are handled is different.

Previous lab: Lambda expressions and functional interfaces · Next lab: Collecting a stream

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these