nerdexam
Oracle

1Z0-809 · Question #216

Given the code fragment: List<String> words = Arrays.asList("win", "try", "best", "luck", "do"); Predicate<String> test1 = w -> { System.out.println("Checking..."); // line n1 return w.equals("do")…

The correct answer is C. Checking... Checking. Option C is correct because the two filters are chained: test2 (length > 3) passes exactly two words - "best" and "luck" - and then test1 executes on each of those two survivors, printing "Checking..." once per element, giving two printed lines. Why the distractors are wrong: A…

Question

Given the code fragment: List<String> words = Arrays.asList("win", "try", "best", "luck", "do"); Predicate<String> test1 = w -> { System.out.println("Checking..."); // line n1 return w.equals("do"); }; Predicate test2 = (String w) -> w.length() > 3; // line n2 words.stream() .filter(test2) .filter(test1) .count(); What is the result?

Options

  • AA compilation error occurs at line n1.
  • BChecking...
  • CChecking... Checking...
  • DA compilation error occurs at line n2.

How the community answered

(67 responses)
  • A
    9% (6)
  • B
    3% (2)
  • C
    75% (50)
  • D
    13% (9)

Explanation

Option C is correct because the two filters are chained: test2 (length > 3) passes exactly two words - "best" and "luck" - and then test1 executes on each of those two survivors, printing "Checking..." once per element, giving two printed lines.

Why the distractors are wrong:

  • A - No error at line n1; a Predicate<String> lambda with a block body containing System.out.println is perfectly legal Java.
  • B - Only one line would print if only one word survived test2, but both "best" and "luck" have length 4 (> 3), so two words reach test1.
  • D - Predicate (raw type) at line n2 generates an unchecked warning, not a compilation error; the explicit (String w) type annotation in the lambda keeps it compilable.

Memory tip: When filters are chained, mentally run each filter as a "gate" and count how many elements exit the last gate before the print - that count equals how many times the println fires.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice