1Z0-809 · Question #58
Given the code fragment: List<String> listVal = Arrays.asList("Joe", "Paul", "Alice", "Tom"); System.out.println ( // line n1 ); Which code fragment, when inserted at line n1, enables the code to…
The correct answer is A. listVal.stream().filter(x -> x.length()>3).count(). Option A is correct because filter() is the appropriate intermediate operation for selecting elements that match a predicate - it passes only the strings with length greater than 3 ("Paul" and "Alice") downstream, and count() is a terminal operation on Stream<T> that returns a…
Question
Options
- AlistVal.stream().filter(x -> x.length()>3).count()
- BlistVal.stream().map(x -> x.length()>3).count()
- ClistVal.stream().peek(x -> x.length()>3).count().get()
- DlistVal.stream().filter(x -> x.length()>3).mapToInt(x -> x).count()
How the community answered
(31 responses)- A74% (23)
- B3% (1)
- C6% (2)
- D16% (5)
Explanation
Option A is correct because filter() is the appropriate intermediate operation for selecting elements that match a predicate - it passes only the strings with length greater than 3 ("Paul" and "Alice") downstream, and count() is a terminal operation on Stream<T> that returns a long with the number of remaining elements, yielding 2.
Option B uses map(x -> x.length() > 3), which transforms each string into a Boolean (true/false) rather than removing elements - the stream still has 4 elements, so count() returns 4 instead of 2. Option C uses peek(), which is a pass-through side-effect operation that never filters anything, and critically, count() returns a primitive long, not an Optional, so calling .get() on it causes a compilation error. Option D applies filter() correctly but then tries mapToInt(x -> x) on the filtered Stream<String>, which fails to compile because a String cannot be directly converted to an int without a mapping function like x -> x.length().
Memory tip: Think "filter → count" as a two-step recipe - filter is the gatekeeper that removes unwanted elements, and count tallies the survivors. Any other intermediate operation (map, peek) lets all elements through and changes the stream's type or inspects elements but never removes them.
Community Discussion
No community discussion yet for this question.