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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP