面试官:java8新增的stream api用过吗?
我:这个必须用过啊。
面试官:给你下面一个字符串数组,如果用stream api来实现,找出以字符'a'开头长度最大的字符串,使用stream api该怎么实现呢?
{"abb","abcd","fegc","efe","adfes"}
我:用下面这个方法来实现:
public static void maxLength(List<String> list){
System.out.println(list.stream().filter(s -> s.startsWith("a")).mapToInt(r -> length(r)).max().orElse(0));;
}
面试官:这个操作是迭代一次还是迭代两次呢?也就是说是先迭代一遍,过滤出以字符'a'开头的字符串数组,然后再迭代一次,找出最大长度,还是一次迭代完成呢?
我:这个是迭代一次完成,如果要是迭代多次,stream后面的操作函数很多的情况下效率会非常低。我们加个打印可以来验证结果,代码如下:
public static void main(String[] args) {
List<String> list = Arrays.asList("abb", "abcd", "fegc", "efe", "adfes");
int maxLength = list.stream().
filter(s -> isStartWitha(s)).
mapToInt(StreamTest1::length).
max().orElse(0);
System.out.println("以字符a开头的字符串最大长度:" + maxLength);
}
private static boolean isStartWitha(String a){
System.out.println(a + " is start with a:" + a.startsWith("a"));
return a.startsWith("a");
}
private static int length(String a){
System.out.println("the length of" + a + ":" + a.length());
return a.length();
}
打印结果如下:
abb is start with a:true
the length of abb:3
abcd is start with a:true
the length of abcd:4
fegc is start with a:false
efe is start with a:false
adfes is start with a:true
the length of adfes:5
以字符a开头的字符串最大长度:5
面试官:你确定只是迭代一次吗?有其他情况吗?
我:有。filter是一个无状态的中间操作,对于这个中间操作来说,stream处理只需要迭代一次。但是对于有状态的中间操作,就需要迭代多次。
面试官