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 妈妈生日祝福语简短励志