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 方法的用法不正確。