Junior — Middle
Can you explain what is meant by a terminal operation in the context of data stream processing?
sobes.tech AI
Answer from AI
In the context of Java Stream API, a terminal operation is an operation that completes the processing of a data stream and returns a result or a side effect. After executing a terminal operation, the stream is considered "consumed" and cannot be used further.
Examples of terminal operations: collect(), forEach(), reduce(), count(), anyMatch(), findFirst().
For example:
List<String> names = List.of("Anna", "Bob", "Charlie");
long count = names.stream()
.filter(name -> name.startsWith("A"))
.count(); // terminal operation
Here, count() is a terminal operation that triggers the computation and returns the number of elements satisfying the condition.