Sobes.tech
Junior — Middle

Is the forEach method in Java a terminal point or an intermediate step in stream processing?

sobes.tech AI

Answer from AI

In Java, the forEach method for streams (Stream.forEach) is a terminal operation, meaning it is the point at which the stream processing ends. After calling forEach, the stream is considered consumed and further operations on it are not possible.

Example:

Stream.of(1, 2, 3)
      .filter(n -> n > 1)  // intermediate operation
      .forEach(System.out::println);  // terminal operation

Here, filter is an intermediate operation, and forEach is a terminal operation that triggers the execution of the entire pipeline and outputs the elements.

Is the forEach method in Java a terminal point or an… - sobes.tech