Sobes.tech
Junior — Middle

Kas saaksite selgitada, mida tähendab termin 'mitte-terminalne operatsioon' andmevoogudega töötamisel Stream API-s?

sobes.tech AI

Vastus AI-lt

In the Java Stream API, operations are divided into terminal and non-terminal (intermediate) operations.

A non-terminal operation is one that returns a new Stream and does not immediately start data processing. It is used to build a chain of transformations, such as filtering, mapping, sorting.

Examples of non-terminal operations:

  • filter()
  • map()
  • sorted()
  • distinct()

These operations are lazy: they are not executed until a terminal operation is invoked, such as forEach(), collect(), count().

Example:

List<String> list = Arrays.asList("a", "bb", "ccc");

list.stream()
    .filter(s -> s.length() > 1) // non-terminal
    .map(String::toUpperCase)    // non-terminal
    .forEach(System.out::println); // terminal

Thus, non-terminal operations allow building a chain of transformations, while the terminal operation initiates execution.