Predicate接口在Java的lambda表达式中的重要性?
Predicate<T>是一个泛型函数接口,表示单个参数函数,该函数返回布尔值(true或false)。此接口在java.util.function包中可用,并且包含用于评估给定参数谓词的test(Tt)方法。
语法
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 classclass 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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短