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 :」。第19行的ifPresent方法,因為Optional物件中有「pen」字串的存在,因此會執行標準輸出串流物件的print方法,輸出「pen」。