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…
Question
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)- A16% (4)
- B8% (2)
- C72% (18)
- D4% (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 returnsOptional<String>, notString, so assigning it to a bareStringwon't compile; andfindAny()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 returnsvoid, so you can't capture a result. - D is a type mismatch:
anyMatch()returns a primitiveboolean(true/false), not anOptional<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
Community Discussion
No community discussion yet for this question.