Given the code fragment:

List<String> str = Arrays.asList("my", "pen", "is", "your", "pen");
Predicate<String> test = s -> {
    int i = 0;
    boolean result = s.contains("pen");
    System.out.print(i++ + " : ");
    return result;
};
str.stream()
        .filter(test)
        .findFirst()
        .ifPresent(System.out::print);

What is the result?

A.

0 : 0 : pen

B.

0 : 1 : pen

C.

0 : 0 : 0 : 0 : 0 : pen

D.

0 : 1 : 2 : 3 : 4 :

E. A compilation error occurs.

題解

程式第 18 行的 filter 方法只會保留包含「pen」子字串的字串元素。第 14 行的「i++」可以直接看成 0,因為 i 是區域變數,所以每次取值都會是 0。程式第 19 行使用了 findFirst 方法,會使得第 18 行的 filter 方法找到第一個符合「保留包含『pen』子字串的字串元素」後,就直接回傳結果。因此程式會找到索引 1 的「pen」,然後將「pen」字串物件包成 Optional 後回傳,此時程式輸出「0 : 0 :」。第 20 行的 ifPresent 方法,因為 Optional 物件中有「pen」字串的存在,因此會執行標準輸出串流物件的 print 方法,輸出「pen」。