Sobes.tech
Junior — Middle

What is the difference between intermediate and terminal operations in stream computations?

sobes.tech AI

Answer from AI

In Java streams, operations are divided into intermediate and terminal.

  • Intermediate operations return a new stream and are lazy — they are not executed immediately but are deferred until a terminal operation is invoked. Examples: filter(), map(), sorted().

  • Terminal operations initiate the processing of the stream and return a result or a side effect. After their invocation, the stream is considered closed. Examples: collect(), forEach(), reduce().

Example:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie");

List<String> filtered = names.stream()
    .filter(name -> name.startsWith("A")) // intermediate
    .map(String::toUpperCase)              // intermediate
    .collect(Collectors.toList());         // terminal

Here, filtering and transformation are not performed until collect() is called, which triggers the entire stream processing.

What is the difference between intermediate and… - sobes.tech