Sobes.tech
Junior — Middle

What is the principle of lazy evaluation in data streams?

sobes.tech AI

Answer from AI

The principle of lazy evaluation in Java Stream data pipelines means that intermediate operations (such as filter, map) are not executed immediately upon their invocation. Instead, they are accumulated and only actually processed when a terminal operation (such as collect, forEach) is called. This allows for optimization of execution, avoiding unnecessary computations and data passes.

Example:

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream()
    .filter(s -> {
        System.out.println("filter: " + s);
        return s.startsWith("a");
    });
// The filter is not executed here

stream.forEach(System.out::println); // The terminal operation triggers processing

In this example, the output "filter: ..." will only appear when forEach is called, not when the stream is created.

What is the principle of lazy evaluation in data… - sobes.tech