Examining Elements in a Stream – Streams
Examining Elements in a Stream
The peek() operation allows stream elements to be examined at the point where the operation is used in the stream pipeline. It does not affect the stream in any way, as it only facilitates a side effect via a non-interfering consumer specified as an argument to the operation. It is primarily used for debugging the pipeline by examining the elements at various points in the pipeline.
The following method is defined in the Stream<T> interface, and an analogous method is also defined in the IntStream, LongStream, and DoubleStream interfaces:
Stream<T> peek(Consumer<? super T> action)
Returns a stream consisting of the same elements as those in this stream, but additionally performs the provided non-interfering action on each element as elements are processed from this stream.
This is a stateless intermediate operation that does not change the stream size, the stream element type, or the encounter order.
By using the peek() method, we can dispense with explicit print statements that were inserted in the implementation of the behavioral parameter of the map() operation in Example 16.4, p. 909. Example 16.6 shows how the peek() operation can be used to trace the processing of elements in the pipeline. A peek() operation after each intermediate operation prints pertinent information which can be used to verify the workings of the pipeline. In Example 16.6, the output shows that the skip() operation before the map() operation can improve performance, as the skip() operation shortens the stream on which the map() operation should be performed.
Example 16.6 Examining Stream Elements
import java.util.List;
public final class OrderOfOperationsWithPeek {
public static void main(String[] args) {
System.out.println(“map() before skip():”);
List<String> cdTitles1 = CD.cdList
.stream()
.map(CD::title)
.peek(t -> System.out.println(“After map: ” + t))
.skip(3)
.peek(t -> System.out.println(“After skip: ” + t))
.toList();
System.out.println(cdTitles1);
System.out.println();
System.out.println(“skip() before map():”); // Preferable.
List<String> cdTitles2 = CD.cdList
.stream()
.skip(3)
.peek(cd -> System.out.println(“After skip: ” + cd))
.map(CD::title)
.peek(t -> System.out.println(“After map: ” + t))
.toList();
System.out.println(cdTitles2);
}
}
Output from the program:
map() before skip():
After map: Java Jive
After map: Java Jam
After map: Lambda Dancing
After map: Keep on Erasing
After skip: Keep on Erasing
After map: Hot Generics
After skip: Hot Generics
[Keep on Erasing, Hot Generics]
skip() before map():
After skip: <Genericos, “Keep on Erasing”, 8, 2018, JAZZ>
After map: Keep on Erasing
After skip: <Genericos, “Hot Generics”, 10, 2018, JAZZ>
After map: Hot Generics
[Keep on Erasing, Hot Generics]
Leave a Reply