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 questions
Answer options
A: 0 : 0 : pen Correct answer
B: 0 : 1 : pen
C: 0 : 0 : 0 : 0 : 0 : pen
D: 0 : 1 : 2 : 3 : 4 :
E: A compilation error occurs.
Correct Answer:
A. 0 : 0 : pen
Explanation

The 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".

Why Incorrect

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.

References

- 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.

Scroll to Top