Senior
What are intermediate and terminal operators in Stream? Provide examples.
sobes.tech AI
Answer from AI
In Java Stream API, operators are divided into intermediate and terminal.
Intermediate operators return a new Stream and allow chaining operations. They are lazy, meaning they do not execute until a terminal operator is called.
Examples of intermediate operators:
filter(Predicate)— filtering elementsmap(Function)— transforming elementssorted()— sortingdistinct()— removing duplicates
Terminal operators end the chain and return a result (not a Stream). They trigger the execution of all intermediate operations.
Examples of terminal operators:
collect(Collector)— collecting elements into a collectionforEach(Consumer)— performing an action for each elementreduce(BinaryOperator)— folding elementscount()— counting elements
Example:
List<String> names = List.of("Anna", "Bob", "Alice", "Brian");
long count = names.stream()
.filter(name -> name.startsWith("A")) // intermediate operator
.count(); // terminal operator
System.out.println(count); // Will output 2