Sobes.tech
Junior — Middle

Kuidas erinevad terminali- ja mitte-terminalioperatsioonid Stream API-s nende funktsioonide ja eesmärgi poolest?

sobes.tech AI

Vastus AI-lt

In the Stream API, terminal and non-terminal operations differ in purpose and behavior:

  • Non-terminal (intermediate) — are operations that return a new stream and allow building a chain of transformations. They are lazy, meaning they do not execute immediately, but only when a terminal operation is invoked. Examples: filter(), map(), sorted(), distinct().

  • Terminal — end the chain of operations and initiate data processing. They return a result (e.g., a collection, a number, void). After a terminal operation, the stream is considered closed and cannot be reused. Examples: collect(), forEach(), reduce(), count().

Example:

List<String> result = list.stream()
    .filter(s -> s.startsWith("A"))   // non-terminal
    .map(String::toUpperCase)           // non-terminal
    .collect(Collectors.toList());     // terminal

Here, filtering and transformation are not performed immediately, but only when collect() is called, which starts processing and returns the final list.