Java8:Stream概念的细化,讨论延迟计算/惰性求值Lazy Evaluations。
Java中常见的逻辑操作be1&&f(),是短路/short-circuiting计算,避免了执行不必要的表达式或方法调用。它使用的就是惰性求值或者说正常顺序/normal order(SICP中译为正则序);与此同时,方法实参的求值是饥饿或者说应用序/applicative order,在方法被调用前,所有的实参通通被求值,即使方法中不使用某些实参也被求值。
JDK中,Stream的中间函数如 filter(Predicate super T>)是惰性求值的,filter并非对流中所有元素调用传递给它的Predicate,Java8:Stream概念中我们见过,调换map()和filter()函数的调用顺序,可以减少函数执行的次数。我们可以借鉴它,设计方法实参的惰性求值,手段是将形参转化为函数接口,因为实参的lambda表达式在被调用时才求值。
例如有一个方法执行很长时间的运算(sleep模拟)后返回i>0。
public static boolean isPositive(int i) {
pln("test ..." + i);
sleep(1000);//
return i > 0;
}
因为方法实参的求值是饥饿的,对于下面的代码
public static void eagerTest(boolean be1, boolean be2) {//方法实参的求值是饥饿的
pln(be1 && be2); //实参
isPositive(-1) && isPositive(2); //&&是短路的
}执行eagerTest(isPositive(-1), isPositive(2));的输出为:
test ...-1
test ...2
false
test ...-1
false
实参的lambda表达式在被调用时才求值
public static void lazyTest(Supplier supplier1, Supplier supplier2) {
pln((supplier1.get() && supplier2.get()));
}
static class imp implements Supplier{
@Override public Boolean get(){
return isPositive(-2);
}
}
public static void test() {
//eagerTest(isPositive(-1), isPositive(2));
pln("lazyTest-------------1");
lazyTest(() -> isPositive(-1), () -> isPositive(2));
pln("lazyTest-------------2");
lazyTest( new imp(), () -> isPositive(2) );
pln("lazyTest-------------3");
lazyTest( new Supplier(){
@Override public Boolean get(){
return isPositive(-3);
}
}, () -> isPositive(3) );
}执行test()的输出为:
lazyTest-------------1
test ...-1
false
lazyTest-------------2
test ...-2
false
lazyTest-------------3
test ...-3
false
在进入lazyTest方法体之前,作为实参的两个lambda表达式并没有求值,而在调用supplier1.get()时才会求值。