Sobes.tech
Junior — Middle

Can you explain what a terminal method in the Stream API is and how it is used?

sobes.tech AI

Answer from AI

A terminal method in the Stream API is a method that completes the chain of operations on a data stream and returns a result. After calling a terminal method, the stream is considered consumed and can no longer be used.

Examples of terminal methods:

  • collect() — gathers elements into a collection or another container.
  • forEach() — performs an action for each element.
  • reduce() — reduces elements to a single value.
  • count() — returns the number of elements.
  • anyMatch(), allMatch(), noneMatch() — check conditions.

Using a terminal method initiates data processing that was previously lazy. For example:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
long count = names.stream()
    .filter(name -> name.length() > 3) // intermediate operation
    .count(); // terminal method
System.out.println(count); // Will output 2

Here, count() is a terminal method that triggers the computation and returns the number of elements satisfying the filter.