Sobes.tech
Junior — Middle

Can you explain what a terminal operation in Stream API is and how it works?

sobes.tech AI

Answer from AI

Terminal operation in Stream API is an operation that completes the processing of a stream and returns a result or a side effect. After calling a terminal operation, the stream is considered consumed and cannot be used further.

Examples of terminal operations:

  • forEach — performs an action for each element
  • collect — gathers elements into a collection
  • reduce — reduces elements to a single value
  • count — counts the number of elements

Terminal operations trigger the execution of all intermediate operations (lazy evaluation) that were not executed before.

Example:

List<String> list = Arrays.asList("a", "bb", "ccc");
long count = list.stream()
    .filter(s -> s.length() > 1) // intermediate operation
    .count(); // terminal operation

System.out.println(count); // Will output 2

Here, count() initiates the stream processing and returns the number of elements that satisfy the condition.