Sobes.tech
Senior

How many times will a stream pass through the original collection with two maps and one collect?

sobes.tech AI

Answer from AI

In Java, Stream operations map are intermediate and lazy, while collect is terminal. When chaining two map operations and one collect, the traversal of the original collection occurs once.

This is because Stream does not execute intermediate operations immediately but builds a processing pipeline. Only when a terminal operation (collect) is called does a single pass occur, during which all intermediate operations are applied sequentially to each element.

Example:

List<String> result = list.stream()
    .map(s -> s.trim())
    .map(s -> s.toUpperCase())
    .collect(Collectors.toList());

Here, elements pass through the chain only once: first trimming spaces, then converting to uppercase, and the result is collected into a list.