Sobes.tech
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 elements
  • map(Function) — transforming elements
  • sorted() — sorting
  • distinct() — 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 collection
  • forEach(Consumer) — performing an action for each element
  • reduce(BinaryOperator) — folding elements
  • count() — 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