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 questionsThe 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.
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.
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.
Keep practicing
Take the free 1Z0-809 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other 1Z0-809 practice questions
- Question 2Given: class Student { String course, name, city; public Student (String name, String cou…
- Question 3Given: class Worker extends Thread { CyclicBarrier cb; public Worker(CyclicBarrier cb) { …
- Question 4Given the code fragment: Path file = Paths.get (“courses.txt”); // line n1 Assume the cou…
- Question 5Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment: Path …
- Question 6Given the code fragment:List<String> empDetails = Arrays.asList(“100, Robin, HR”,“200, Ma…
- Question 7Given the code fragment: List str = Arrays.asList (“my”, “pen”, “is”, “your’, “pen”); Pre…
