Java SE 8 Programmer II | Exam 1Z0-809 | Question Analysis

Code Fragment: Find String Elements with Length > 3 | Answer

Question

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 print the count of string elements whose length is greater than three?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The correct code fragment to enable the given code to print the count of string elements whose length is greater than three is option A: listVal.stream().filter(x -> x.length()>3).count().

Let's break down this code fragment to understand how it works:

scss
listVal.stream() // Convert the List to a Stream .filter(x -> x.length() > 3) // Filter the Stream to only include elements whose length is greater than 3 .count() // Count the number of elements in the Stream

The stream() method is used to convert the List to a Stream of String elements. The filter() method is then used to filter the Stream to only include elements whose length is greater than 3. The count() method is then used to count the number of elements remaining in the Stream.

Option B, listVal.stream().map(x -> x.length() > 3).count(), is incorrect because the map() method transforms the stream elements, but we only want to filter them based on their length, not transform them to a boolean. So, using map() in this case would not return the expected result.

Option C, listVal.stream().peek(x -> x.length() > 3).count().get(), is incorrect because peek() is an intermediate operation that allows us to perform some action on each element of the Stream but does not change the elements in the Stream. Moreover, count() returns a long value, not an optional. Therefore, calling .get() on it would result in a compilation error.

Option D, listVal.stream().filter(x -> x.length() > 3).mapToInt(x -> x).count(), is also incorrect because mapToInt() is used to convert Stream<String> to IntStream, which is not necessary in this case as we want to count the number of String elements whose length is greater than 3. Moreover, calling mapToInt(x -> x) would result in a compilation error because String cannot be converted to int.