1Z0-809 practice question 7 of 25
Given the code fragment: List str = Arrays.asList (“my”, “pen”, “is”, “your’, “pen”); Predicate test = s -> { int i = 0; boolean result = s.contains (“pen”); System.out.print(i++) + “:”); return result; }; str.stream() .filter(test) .findFirst() .ifPresent(System.out ::print); What is the result?
Full set: 196 questionsThe findFirst() operation is a short-circuiting terminal operation. The stream processing stops as soon as the first element matching the predicate is found. The predicate test is a lambda expression where the variable i is declared locally. Therefore, i is re-initialized to 0 every time the predicate is invoked.
1. test("my") is called. It prints "0:" and returns false.
2. test("pen") is called. It prints "0:" and returns true. The stream pipeline finds its first match ("pen") and terminates. The ifPresent consumer then prints "pen". The final output is "0:0:pen".
B. The variable i is local to the lambda, so it is reset to 0 on each call and never prints 1.
C. The findFirst() operation is short-circuiting, so the stream does not process all elements after a match is found.
D. The stream is short-circuited, and the local variable i does not persist its value across predicate calls.
E. The code is syntactically correct. A lambda expression can contain multiple statements enclosed in braces.
- Oracle, The Java™ Tutorials, "Aggregate Operations > Short-Circuiting". This section explains that operations like findFirst can terminate processing early.
- Oracle, Java SE 8 Documentation, java.util.stream.Stream#findFirst(). The documentation describes findFirst() as a short-circuiting terminal operation.
- Java Language Specification, SE 8 Edition, §15.27.2. "Lambda Body". This section details that variables declared within a lambda body are local to it.
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 8Which two reasons should you use interfaces instead of abstract classes? (Choose two.)
