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
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)- A3% (1)
- B10% (3)
- C17% (5)
- D70% (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 istrue. - B (
anyMatch(w -> w.equals("Java"))) -anyMatchreturnstrueas soon as any element matches;"Java"is in the list, so it'strue. - C (
findFirst().get().equals("Java")) -findFirst()always returns"Java"(the first element), making the comparisontrue.
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.