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?
A.
listVal.stream().filter(x -> x.length() > 3).count()
B.
listVal.stream().map(x -> x.length() > 3).count()
C.
listVal.stream().peek(x -> x.length() > 3).count().get()
D.
listVal.stream().filter(x -> x.length() > 3).mapToInt(x -> x).count()
题解
Stream 对象的 filter 方法可以保留符合条件的元素;map 和 mapToInt 方法可以用来替换元素;peek 方法可以用来走访所有元素。题目要求找出字符串长度大于三的元素数量。
选项 A,用 filter 方法只保留字符串长度大于三的元素,所以剩下来的元素数量为 2。是正确答案。
选项 B,用 map 方法将所有元素转为 boolean,数量依然为 4。
选项 C,peek 方法的用法不正确。
选项 D,mapToInt 方法的用法不正确。
