Junior — Middle
What behavior is exhibited in the Stream API if there is no call to a terminal operation?
sobes.tech AI
Answer from AI
In Java Stream API, operations are divided into intermediate and terminal. Intermediate operations (e.g., filter, map) are lazy and are not executed until a terminal operation (e.g., collect, forEach) is invoked.
If the terminal operation is not called, the stream will not be processed, and no computations will occur. This means that the chain of intermediate operations will only create a description of the stream but will not execute it.
Example:
Stream.of(1, 2, 3, 4)
.filter(n -> n % 2 == 0)
.map(n -> n * 2);
// No element is processed because there is no terminal operation
To trigger processing, a terminal operation must be called:
List<Integer> result = Stream.of(1, 2, 3, 4)
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.collect(Collectors.toList());
Without a terminal operation, the stream will not be executed.