nerdexam
Oracle

1Z0-809 · Question #124

Given: public class Data { private int x; public Data(int x) { this.x = x; } public int getX() { return x; } } public class Test { public static void main(String[] args) { List<Data> list =…

The correct answer is A. System.out.println(list.stream().filter(d -> d.getX() == 20).findFirst().get().getX()). Option A correctly chains .filter(d -> d.getX() == 20) on a Stream<Data>, so the lambda parameter d is a Data object and getX() returns a primitive int - a safe value comparison. findFirst() returns the first match as Optional<Data>, .get() unwraps it, and .getX() extracts the…

Question

Given: public class Data { private int x; public Data(int x) { this.x = x; } public int getX() { return x; } } public class Test { public static void main(String[] args) { List<Data> list = Arrays.asList(new Data(10), new Data(20), new Data(30)); // line n1 } } Which code fragment, when inserted at line n1, enables the code to print the output 20?

Options

  • ASystem.out.println(list.stream().filter(d -> d.getX() == 20).findFirst().get().getX());
  • BSystem.out.println(list.stream().map(Data::getX).filter(d -> d == 20).findAny().get());
  • CSystem.out.println(list.stream().filter(d -> d.getX() == 20).map(Data::getX).findAny().get());
  • DSystem.out.println(list.stream().map(Data::getX).filter(d -> d == 20).findFirst().get());

How the community answered

(25 responses)
  • A
    84% (21)
  • B
    4% (1)
  • C
    8% (2)
  • D
    4% (1)

Explanation

Option A correctly chains .filter(d -> d.getX() == 20) on a Stream<Data>, so the lambda parameter d is a Data object and getX() returns a primitive int - a safe value comparison. findFirst() returns the first match as Optional<Data>, .get() unwraps it, and .getX() extracts the integer 20.

Options B and D are wrong because they call map(Data::getX) first, converting the stream to Stream<Integer>. The subsequent filter(d -> d == 20) then uses == to compare boxed Integer objects rather than primitive values - a classic Java trap where == tests reference equality, not value equality, which fails for integers outside the cached range (−128 to 127). While 20 happens to be cached and would work at runtime, this is considered incorrect and unreliable code.

Option C is wrong because findAny() provides no ordering guarantee - it's designed for parallel streams where any matching element may be returned. Even though only one element passes the filter here, exams penalize its use where a deterministic result is required; findFirst() is the correct choice for guaranteed ordering.

Memory tip: Map late, filter early. Keep your stream typed as domain objects (Stream<Data>) while filtering so you get safe primitive comparisons via getters, then extract values at the end. Whenever you see == applied to a Stream<Integer>, treat it as a red flag.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice