Java 中 lambda 表示式中謂詞介面的重要性?


Predicate<T> 是一個泛型函式介面,表示返回布林值(真或假)的單引數函式。此介面在java.util.function 包中可用,包含一個 test(T t) 方法,用於評估特定引數的謂詞。

語法

public interface Predicate {
 boolean test(T t);
}

示例

import java.util.*;
import java.util.functionPredicate;

public class LambdaPredicateTest {
   public static void main(String args[]) {
      Employee emp1 = new Employee("Raja", 26);
      Employee emp2 = new Employee("Jaidev", 24);
      Employee emp3 = new Employee("Adithya", 30);

      List<Employee> empList = new ArrayList<Employee>();
      empList.add(emp1);
      empList.add(emp2);
      empList.add(emp3);

      Predicate<Employee> predicateForAge = (e) -> e.age >= 25;
      Predicate<Employee> predicateForName = (e) -> e.name.startsWith("A");
      for(Employee emp : empList) {
         if(predicateForAge.test(emp)) {
            System.out.println(emp.name +" is eligible by age");
         }
      }
      System.out.println("----------------------------");
      for(Employee emp : empList) {
         if(predicateForName.test(emp)) {
            System.out.println(emp.name +" is eligible by name");
         }
      }
   }
}

// Employee class
class Employee {
   public String name;
   public int age;
   public Employee(String name,int age){
      this.name=name;
      this.age=age;
   }
}

輸出

Raja is eligible by age
Adithya is eligible by age
----------------------------
Adithya is eligible by name

更新時間:2020 年 7 月 11 日

2K+ 檢視次數

開啟你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.