文章目录[隐藏]
一、前言
Java 8中引入了Predicate
功能接口。
Java Predicate
表示一个参数的谓词。
Predicate
是一个布尔值的函数。
Java Predicate
是一个功能接口,属于java.util.function
包。
Predicate
的功能方法是test(T t)
。
Predicate
的其他方法是test
、isEqual
、and
、or
、negate
和not
。
not
方法在Java 11中被引入。
在本文章,我们将提供Predicate
的例子及其所有方法。
二、test(T t)
boolean test(T t)
test
是Predicate
的功能方法。它在给定的参数上评估这个谓词。
例1:
PredicateTestDemo1.java
import java.util.function.Predicate; public class PredicateTestDemo1 { public static void main(String[] args) { // Is username valid Predicate<String> isUserNameValid = u -> u != null && u.length() > 5 && u.length() < 10; System.out.println(isUserNameValid.test("Mahesh")); //true // Is password vali<p style="color:transparent">本文来源gao!daima.com搞$代!码网</p>d Predicate<String> isPasswordValid = p -> p != null && p.length() > 8 && p.length() < 15; System.out.println(isPasswordValid.test("Mahesh123")); //true // Word match Predicate<String> isWordMatched = s -> s.startsWith("Mr."); System.out.println(isWordMatched.test("Mr. Mahesh")); //true //Odd numbers Predicate<Integer> isEven = n -> n % 2 == 0; for(int i = 0 ; i < 5 ; i++) { System.out.println("Is "+ i + " even: " + isEven.test(i)); } } }
输出结果
true
true
true
Is 0 even: true
Is 1 even: false
Is 2 even: true
Is 3 even: false
Is 4 even: true
例2:
PredicateTestDemo2.java
import java.util.function.Function; import java.util.function.Predicate; public class PredicateTestDemo2 { public static void main(String[] args){ Predicate<Student> maleStudent = s-> s.getAge() >= 20 && "male".equals(s.getGender()); Predicate<Student> femaleStudent = s-> s.getAge() > 18 && "female".equals(s.getGender()); Function<Student,String> maleStyle = s-> "Hi, You are male and age "+s.getAge(); Function<Student,String> femaleStyle = s-> "Hi, You are female and age "+ s.getAge(); Student s1 = new Student("Gauri", 20,"female"); if(maleStudent.test(s1)){ System.out.println(s1.customShow(maleStyle)); }else if(femaleStudent.test(s1)){ System.out.println(s1.customShow(femaleStyle)); } }
Student.java
import java.util.function.Function; public class Student { private String name; private int age; private String gender; private int marks; public Student(String name, int age, String gender){ this.name = name; this.age = age; this.gender = gender; } public Student(String name, int age, String gender, int marks){ this.name = name; this.age = age; this.gender = gender; this.marks = marks; } public String getName() { return name; } public int getAge() { return age; } public String getGender() { return gender; } public int getMarks() { return marks; } public String customShow(Function<Student,String> fun){ return fun.apply(this); } public String toString(){ return name+" - "+ age +" - "+ gender + " - "+ marks; } }