Junior — Middle
Can you name two main types of operations implemented using Stream API?
sobes.tech AI
Answer from AI
Two main types of operations in Java Stream API:
-
Intermediate operations — return a new stream and allow chaining of operations. They are lazy, meaning they do not execute until a terminal operation is invoked. Examples:
filter(),map(),sorted(),distinct(). -
Terminal operations — terminate the chain and return a result (such as a collection, a number, or void). After a terminal operation, the stream is considered consumed. Examples:
collect(),forEach(),reduce(),count().
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
long count = names.stream()
.filter(name -> name.startsWith("A")) // intermediate operation
.count(); // terminal operation
Here, filter is an intermediate operation, and count is a terminal operation.