nerdexam
Oracle

1Z0-819 · Question #51

Given var fruits = List.of("apple", "orange", "banana", "lemon"); You want to examine the first element that contains the character 'n'. Which statement will accomplish this?

The correct answer is C. Optional<String> result = fruits.stream().filter(f -> f.contains("n")).findFirst(). Option C is correct because findFirst() returns an Optional<String> - it searches the stream in encounter order and returns the first element matching the filter, wrapped in an Optional to handle the case where no match exists. Why the others fail: A fails on two counts…

Working with Streams and Lambda Expressions

Question

Given var fruits = List.of("apple", "orange", "banana", "lemon"); You want to examine the first element that contains the character 'n'. Which statement will accomplish this?

Options

  • AString result = fruits.stream().filter(f -> f.contains("n")).findAny();
  • Bfruits.stream().filter(f -> f.contains("n")).forEachOrdered(System.out::print);
  • COptional<String> result = fruits.stream().filter(f -> f.contains("n")).findFirst();
  • DOptional<String> result = fruits.stream().anyMatch(f -> f.contains("n"));

How the community answered

(25 responses)
  • A
    16% (4)
  • B
    8% (2)
  • C
    72% (18)
  • D
    4% (1)

Explanation

Option C is correct because findFirst() returns an Optional<String> - it searches the stream in encounter order and returns the first element matching the filter, wrapped in an Optional to handle the case where no match exists.

Why the others fail:

  • A fails on two counts: findAny() also returns Optional<String>, not String, so assigning it to a bare String won't compile; and findAny() makes no order guarantee anyway, meaning it wouldn't reliably return the first match.
  • B uses forEachOrdered, which prints matching elements as a side effect but stores nothing in a variable - it returns void, so you can't capture a result.
  • D is a type mismatch: anyMatch() returns a primitive boolean (true/false), not an Optional<String>, so the assignment won't compile.

Memory tip: Think "First → findFirst()Optional." Any terminal operation that finds an element (findFirst, findAny) always returns Optional<T> because the stream might be empty. Operations that check existence (anyMatch, allMatch) return boolean, and operations that consume elements (forEach, forEachOrdered) return void.

Topics

#Stream API#findFirst()#Optional#Terminal Operations

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice