Sobes.tech
Junior — Middle

What is the difference between peek and forEach when working with streams in the Stream API?

sobes.tech AI

Answer from AI

In Java Stream API, the methods peek and forEach have different purposes and characteristics:

  • peek — an intermediate operation that allows you to perform an action on each element of the stream without modifying the stream itself. It is usually used for debugging or logging. Since it is an intermediate operation, it is lazily executed and does not run until a terminal operation is invoked.

  • forEach — a terminal operation that performs an action on each element of the stream and completes the processing. After calling forEach, the stream is considered consumed and cannot be used further.

Example:

Stream.of(1, 2, 3)
    .peek(i -> System.out.println("peek: " + i)) // debugging
    .map(i -> i * 2)
    .forEach(i -> System.out.println("forEach: " + i));

Here, peek outputs the elements before transformation, and forEach outputs after. If only peek is called without a terminal operation, the code will not execute.