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」。
