Streams Peek

Description

We can debug a stream by using the peek(Consumer<? super T> action) method of the Stream<T> interface.

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

We can use a lambda expression with the peek() method to log elements.

Example

The following code uses the peek() method to print the elements passing through the stream pipeline:


import java.util.stream.Stream;
//  w ww  .j  a v  a  2s .co m
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);

  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial