Junior — Middle
Can you list the main operations performed at the end of data streaming processing?
sobes.tech AI
Answer from AI
In Java Stream API, operations are divided into intermediate and terminal (end) operations. At the end of data stream processing, a terminal operation is always invoked, which triggers the computations and returns a result or side effect.
Main terminal operations:
- collect() — collects stream elements into a collection or another container.
- forEach() — performs an action for each element (usually for side effects).
- reduce() — reduces elements to a single value using an accumulator.
- count() — returns the number of elements.
- anyMatch(), allMatch(), noneMatch() — check if elements match a condition.
- findFirst(), findAny() — return the first or any element if present.
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
long count = names.stream()
.filter(name -> name.startsWith("A"))
.count();
System.out.println(count); // Outputs the number of names starting with "A"
Without a terminal operation, the stream will not be processed.