Senior
Mis on vahe- ja lõppmeetodid voogudes?
sobes.tech AI
Vastus AI-lt
In Java Stream API, methods are divided into intermediate and terminal.
-
Intermediate methods return a new stream and allow chaining operations. They are lazy, meaning they do not execute immediately, but only when a terminal method is called. Examples:
filter(),map(),sorted(),distinct(). -
Terminal methods initiate stream processing and return a result (not a stream). After their invocation, the chain ends. Examples:
collect(),forEach(),reduce(),count().
Example:
List<String> names = List.of("Anna", "Bob", "Charlie", "David");
long count = names.stream() // intermediate method stream()
.filter(name -> name.length() > 3) // intermediate method filter()
.count(); // terminal method count()
System.out.println(count); // Prints the number of names longer than 3 characters