nerdexam
Oracle

1Z0-809 · Question #198

Given the code fragment: List<String> cs = Arrays.asList("Java", "Java EE", "Java ME"); // line n1 System.out.print(b); Which code fragment, when inserted at line n1, ensures false is printed?

The correct answer is D. boolean b = cs.stream().allMatch(w -> w.equals("Java")). D is correct because allMatch returns true only if every element in the stream satisfies the predicate. Since the list contains "Java EE" and "Java ME" - which do not equal "Java" - allMatch short-circuits on the second element and returns false. Why the distractors fail: A…

Question

Given the code fragment: List<String> cs = Arrays.asList("Java", "Java EE", "Java ME"); // line n1 System.out.print(b); Which code fragment, when inserted at line n1, ensures false is printed?

Options

  • Aboolean b = cs.stream().findAny().get().equals("Java");
  • Bboolean b = cs.stream().anyMatch(w -> w.equals("Java"));
  • Cboolean b = cs.stream().findFirst().get().equals("Java");
  • Dboolean b = cs.stream().allMatch(w -> w.equals("Java"));

How the community answered

(30 responses)
  • A
    3% (1)
  • B
    10% (3)
  • C
    17% (5)
  • D
    70% (21)

Explanation

D is correct because allMatch returns true only if every element in the stream satisfies the predicate. Since the list contains "Java EE" and "Java ME" - which do not equal "Java" - allMatch short-circuits on the second element and returns false.

Why the distractors fail:

  • A (findAny().get().equals("Java")) - findAny() on a sequential stream typically returns the first element, "Java", so the equals check is true.
  • B (anyMatch(w -> w.equals("Java"))) - anyMatch returns true as soon as any element matches; "Java" is in the list, so it's true.
  • C (findFirst().get().equals("Java")) - findFirst() always returns "Java" (the first element), making the comparison true.

Memory tip: Think of the prefix: allMatch = all or nothing. If even one element fails the test, the whole thing is false. When you see a mixed list and a strict single-value predicate, allMatch is your go-to for forcing false.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice