积极求值与惰性求值

积极求值意味着表达式一遇到就求值,而惰性求值是指在需要时才求值。请参阅以下示例以了解这一概念。

import java.util.function.Supplier;

public class FunctionTester {
   public static void main(String[] args) {
      String queryString = "password=test";
      System.out.println(checkInEagerWay(hasName(queryString)
         , hasPassword(queryString)));
      System.out.println(checkInLazyWay(() -> hasName(queryString)
         , () -> hasPassword(queryString)));
   }

   private static boolean hasName(String queryString){
      System.out.println("Checking name: ");
      return queryString.contains("name");
   }

   private static boolean hasPassword(String queryString){
      System.out.println("Checking password: ");
      return queryString.contains("password");
   } 

   private static String checkInEagerWay(boolean result1, boolean result2){
      return (result1 && result2) ? "all conditions passed": "failed.";
   }

   private static String checkInLazyWay(Supplier<Boolean> result1, Supplier<Boolean> result2){
      return (result1.get() && result2.get()) ? "all conditions passed": "failed.";
   }
}

输出

Checking name: 
Checking password: 
failed.
Checking name: 
failed.

此处 checkInEagerWay() 函数首先评估参数,然后执行其语句。而 checkInLazyWay() 则执行其语句并根据需要评估参数。由于 && 是短路运算符,checkInLazyWay 仅评估第一个参数(结果为 false),而根本不评估第二个参数。