Java Reference
In-Depth Information
the method divideByZero is reported correctly in the stack trace:
In general, keep in mind that stack traces involving lambda expressions may be more difficult to
understand. This is an area where the compiler can be improved in a future version of Java.
8.4.2. Logging information
Let's say you're trying to debug a pipeline of operations in a stream. What can you do? You could
use forEach to print or log the result of a stream as follows:
List<Integer> numbers = Arrays.asList(2, 3, 4, 5);
numbers.stream()
.map(x -> x + 17)
.filter(x -> x % 2 == 0)
.limit(3)
.forEach(System.out::println);
It will produce the following output:
20
22
Unfortunately, once you call forEach, the whole stream is consumed. What would be really
useful is to understand what each operation (map, filter, limit) produces in the pipeline of a
stream.
This is where the stream operation peek can help. Its purpose is to execute an action on each
element of a stream as it's consumed. But it doesn't consume the whole stream like forEach does;
it forwards the element it performed an action on to the next operation in the pipeline. Figure
8.4 illustrates the peek operation.
 
Search WWH ::




Custom Search