如何在Java的lambda表达式中使用Predicate 和BiPredicate ?
在java.util中定义的谓词<T>接口。功能包。它表示一个只有一个参数的布尔值函数。它是一种函数接口,其函数方法是test()。BiPredicate<T,U>接口与具有两个参数的Predicate<T>接口类似。它可以用作lambda表达式的赋值目标。
谓词的语法
@FunctionalInterface public interface Predicate<T>
示例
import java.util.*; import java.util.function.*; import java.util.stream.*; public class EmployeePredicateTest { public static void main(String[] args) { Employee e1 = new Employee(1, 23, "M", "Raja"); Employee e2 = new Employee(2, 13, "M", "Jai"); Employee e3 = new Employee(3, 36, "F", "Yamini"); Employee e4 = new Employee(4, 26, "F", "Geetha"); Employee e5 = new Employee(5, 19, "M", "Adithya"); List<Employee> employees = new ArrayList<Employee>(); employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5})); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultMale())); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultFemale())); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35))); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35).negate())); } }// Employee classclass Employee { private Integer id; private Integer age; private String gender; private String name; public Employee(Integer id, Integer age, String gender, String name) { this.id = id; this.age = age; this.gender = gender; this.name = name; } public Integer getAge() { return age; } public String getGender() { return gender; } public String getName() { return name; } @Override public String toString() { return this.name.toString()+" - "+ this.age.toString(); } }// EmployeePredicate classclass EmployeePredicate { public static Predicate isAdultMale() { return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M"); } public static Predicate isAdultFemale() { return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F"); } public static Predicate isAgeMoreThan(Integer age) { return p -> p.getAge() > age; } public static List filterEmployees(List<Employee> employees, Predicate<Employee> predicate) { return employees.stream().filter(predicate).collect(Collectors.<Employee>toList()); } }
输出结果
[Raja - 23] [Yamini - 36, Geetha - 26] [Yamini - 36] [Raja - 23, Jai - 13, Geetha - 26, Adithya - 19]
BiPredicate的语法
@FunctionalInterface public interface BiPredicate<T, U>
示例
import java.util.*; import java.util.function.*; public class BiPredicateTest { public static void main(String[] args) { BiPredicate<Integer, Integer> bi = (x, y) -> x > y; BiPredicate<Integer, Integer> eq = (x, y) -> x -2 > y; System.out.println(bi.test(2, 3)); System.out.println(bi.or(eq).test(2, 3)); System.out.println(bi.or(eq).test(8, 3)); } }
输出结果
false false true