Java SE 11 Developer — Question 39
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?
Answer options
- A. String result = fruits.stream().filter(f −> f.contains(“n”)).findAny();
- B. fruits.stream().filter(f −> f.contains(“n”)).forEachOrdered(System.out::print);
- C. Optional<String> result = fruits.stream().filter(f −> f.contains(“n”)).findFirst ();
- D. Optional<String> result = fruits.stream().anyMatch(f −> f.contains(“n”));
Correct answer: B
Explanation
The correct answer is C, as it correctly uses findFirst() to get the first element that matches the filter condition for containing 'n'. Option A incorrectly uses findAny(), which does not guarantee the first element. Option B uses forEachOrdered() to print the elements, which is not what the question asks for. Option D checks if any elements match the condition but does not retrieve the actual element.