What does lazy evaluation mean in a Java stream, and how can you actually see it happening?
Lazy evaluation means that building the pipeline does no work at all. The work happens later, when you ask for the answer, and only as much work as the answer really needs.
You can see it happening with the method peek, which runs your code for each value as it goes past, without changing it.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan", "Katherine");
// Nothing has happened yet. The pipeline is only a plan.
System.out.println("building the pipeline");
List<String> result = names.stream()
.peek(name -> System.out.println(" looking at " + name))
.filter(name -> name.length() > 4)
.peek(name -> System.out.println(" keeping " + name))
.map(name -> name.toUpperCase())
.collect(Collectors.toList());
System.out.println("the result : " + result);
}
}
The output shows the order of the events. The line about building the pipeline prints first, and nothing else has happened at that point. The first peek only prints when the terminal operation asks for the result, and the values that the filter throws away never reach the second peek at all.
That last point is the important one. The filter threw away two of the four names, and the second peek only saw the two that stayed. The work that was not needed was never done.
The next question in this topic looks at why it works this way and what it makes possible.