Java - Stream Peek Operation


To look at stream elements as they pass through the steps, use the peek(Consumer<? super T> action) method.

It produces a stream after applying an action on each input element.

IntStream, LongStream, and DoubleStream have a peek() method that takes a IntConsumer, a LongConsumer, and a DoubleConsumer as an argument.

The following code uses a lambda expression with the peek() method to log messages describing elements being processed.



public class Main {
  public static void main(String[] args) {
    int sum = Stream.of(1, 2, 3, 4, 5)//
        .peek(e -> System.out.println("Taking integer: " + e))//
        .filter(n -> n % 2 == 1)//
        .peek(e -> System.out.println("Filtered integer: " + e))//
        .map(n -> n * n)//
        .peek(e -> System.out.println("Mapped integer: " + e))//
        .reduce(0, Integer::sum);//

    System.out.println("Sum = " + sum);

  }/*from  w  w  w  .j  a  v  a 2s  .  c  o  m*/