Java 8 Predicate 示例
java.util.function.Predicate是在java 8中引入的functional interface。Predicate用于分配lambda表达式。functional interface是返回布尔值的test(T t)。当我们将对象传递给这个方法时,它将通过分配的lambda表达式来评估对象。
语法介绍:
public static void main(String[] args) {
//接收一个泛型参数,比较返回boolean值
Predicate<String> predicate = (v1) -> {
//此处别的逻辑处理,做简单的语法介绍就不详细写了。
return v1.equals("1");
};
// Predicate<String> predicates = (v1) -> v1.equals("2"); 直接返回结果可这样写
System.out.println(predicate.test("1"));//true
System.out.println(predicate.test("2"));//false
}
找到以下两个表达式
Predicate<Student> maleStudent = s-> s.age >= 20 && "male".equals(s.gender);
Predicate<Student> femaleStudent = s-> s.age > 15 && "female".equals(s.gender);
第一个表达式为男性学生创造了场景,第二个表达式为女学生创造了场景。找到完整的例子
public static void main(String[] args){ Predicate<Student> maleStudent = s-> s.age >= 20 && "male".equals(s.gender); Predicate<Student> femaleStudent = s-> s.age > 15 && "female".equals(s.gender); Function<Student,String> maleStyle = s-> "Hi, You are male and age "+s.age; Function<Student,String> femaleStyle = s-> "Hi, You are female and age "+ s.age; Student s1 = new Student(21,"male"); if(maleStudent.test(s1)){ System.out.println(s1.customShow(maleStyle)); }else if(femaleStudent.test(s1)){ System.out.println(s1.customShow(femaleStyle)); } }
在这个例子中,我们创建了两个Predicate,然后创建一个学生对象,我们将它传递给Predicate的测试方法。
public class Student { public int age; public String gender; public Student(int age,String gender){ this.age = age; this.gender = gender; } public String customShow(Function<Student,String> fun){ return fun.apply(this); }
运行示例,输出如下。
Hi, You are male and age 21