1Z0-809 practice question 12 of 25

Given the code fragment: List values = Arrays.asList (1, 2, 3); values.stream () .map(n -> n*2)//line n1 .peek(System.out::print)//line n2 .count(); What is the result?

Full set: 196 questions
Answer options
A: 246 Correct answer
B: The code produces no output.
C: A compilation error occurs at line n1.
D: A compilation error occurs at line n2.
Correct Answer:
A. 246
Explanation

The code creates a stream from a list of integers. The map operation transforms each element by multiplying it by 2. The peek operation is an intermediate operation that consumes an element, performs an action (printing the element), and passes it to the next stage. Crucially, intermediate operations in a stream pipeline are lazy and are only executed when a terminal operation, such as count(), is invoked. The count() operation traverses the entire stream to count the elements, which triggers the map and peek operations for each element. Thus, 2, 4, and 6 are printed sequentially without spaces.

Why Incorrect

B. The code produces no output. This is incorrect. The terminal operation count() forces the execution of all preceding intermediate operations, including peek.
C. A compilation error occurs at line n1. The expression map(n -> n2) is a valid use of the map method on a Stream.
D. A compilation error occurs at line n2. The expression peek(System.out::print) is a valid use of the peek method with a method reference to System.out.print.

References

1. Oracle, Java SE 8 API Documentation, java.util.stream.Stream.peek(Consumer action). "Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream."

2. Oracle, Java SE 8 API Documentation, java.util.stream.Stream.count(). "This is a terminal operation."

3. Naftalin, M., & Wadler, P. (2014). Java Generics and Collections. O'Reilly Media. Chapter 8 discusses stream processing and laziness.

Scroll to Top