一、前言
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 PredicateisUserNameValid = u -> u != null && u.length() > 5 && u.length() < 10; System.out.println(isUserNameValid.test("Mahesh")); //true // Is password valid Predicate isPasswordValid = p -> p != null && p.length() > 8 && p.length() < 15; System.out.println(isPasswordValid.test("Mahesh123")); //true // Word match Predicate isWordMatched = s -> s.startsWith("Mr."); System.out.println(isWordMatched.test("Mr. Mahesh")); //true //Odd numbers Predicate 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){ PredicatemaleStudent = s-> s.getAge() >= 20 && "male".equals(s.getGender()); Predicate femaleStudent = s-> s.getAge() > 18 && "female".equals(s.getGender()); Function maleStyle = s-> "Hi, You are male and age "+s.getAge(); Function 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(Functionfun){ return fun.apply(this); } public String toString(){ return name+" - "+ age +" - "+ gender + " - "+ marks; } }
输出结果
Hi, You are female and age 20
三、and(Predicate super T> other)
default Predicateand(Predicate super T> other)
and
是Predicate
的默认方法,它返回一个组成的谓词,表示这个谓词和其他谓词的短路逻辑AND
。在评估组成的谓词时,如果这个谓词是假的,那么其他谓词将不会被评估。在错误的情况下,如果此谓词抛出错误,那么其他谓词将不会被评估。
PredicateAndDemo.java
import java.util.function.Predicate; public class PredicateAndDemo { public static void main(String[] args) { PredicateisMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender()); Predicate isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender()); Predicate isStudentPassed = s -> s.getMarks() >= 33; // Testing if male student passed. Student student1 = new Student("Mahesh", 22, "male", 30); Boolean result = isMaleStudent.and(isStudentPassed).test(student1); System.out.println(result); //false // Testing if female student passed. Student student2 = new Student("Gauri", 19, "female", 40); result = isFemaleStudent.and(isStudentPassed).test(student2); System.out.println(result); //true } }
输出
false
true
四、or(Predicate super T> other)
default Predicateor(Predicate super T> other)
or
是Predicate
的默认方法,它返回一个组成的谓词,表示此谓词和其他谓词的短路逻辑OR
。在评估组成的谓词时,如果此谓词为真,那么其他谓词将不会被评估。在错误的情况下,如果此谓词抛出错误,那么其他谓词将不会被评估。
PredicateOrDemo.java
import java.util.function.Predicate; public class PredicateOrDemo { public static void main(String[] args) { PredicateisMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender()); Predicate isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender()); Predicate isStudentPassed = s -> s.getMarks() >= 33; Student student1 = new Student("Mahesh", 22, "male", 35); //Test either male or female student Boolean result = isMaleStudent.or(isFemaleStudent).test(student1); System.out.println(result); //true //Is student passed, too result = isMaleStudent.or(isFemaleStudent).and(isStudentPassed).test(student1); System.out.println(result); //true } }
输出
true
true
五、negate()
default Predicatenegate()
negate
是Predicate
的默认方法,它返回一个表示该谓词的逻辑否定的谓词。如果评估的结果是真的,negate
将使它变成假的,如果评估的结果是假的,negate
将使它变成真的。
PredicateNegateDemo.java
import java.util.function.Predicate; public class PredicateNegateDemo { public static void main(String[] args) { PredicateisNumberMatched = n -> n > 10 && n < 20; //With negate() Boolean result = isNumberMatched.negate().test(15); System.out.println(result); //false //Without negate() result = isNumberMatched.test(15); System.out.println(result); //true Predicate isValidName = s -> s.length() > 5 && s.length() < 15; System.out.println(isValidName.negate().test("Krishna")); //false Predicate isLessThan50 = n -> n < 50; System.out.println(isLessThan50.negate().test(60)); //true Predicate isGreaterThan20 = n -> n > 20; System.out.println(isGreaterThan20.negate().test(30)); //false result = isLessThan50.and(isGreaterThan20).negate().test(25); System.out.println(result); //false } }
输出
false
true
false
true
false
false
六、isEqual(Object targetRef)
staticPredicate isEqual(Object targetRef)
isEqual
是Predicate
的静态方法,它返回测试两个参数是否等于Objects.equals(Object, Object)
的谓词。我们使用Predicate.isEqual
创建predicate
,如下所示。
PredicateisHelloMsg = Predicate.isEqual("Hello"); Predicate isMahabharatBook = Predicate.isEqual(new Book("Mahabharat", "Vyas"));
PredicateIsEqualDemo.java
import java.util.function.Predicate; public class PredicateIsEqualDemo { public static void main(String[] args) { System.out.println("---Testing Hello message---"); PredicateisHelloMsg = Predicate.isEqual("Hello"); System.out.println(isHelloMsg.test("Hello")); //true System.out.println(isHelloMsg.test("Hi")); //false System.out.println("---Testing Mahabharat book---"); Book mahabharatBook = new Book("Mahabharat", "Vyas"); Predicate isMahabharatBook = Predicate.isEqual(mahabharatBook); System.out.println(isMahabharatBook.test(new Book("Mahabharat", "Vyas"))); //true System.out.println(isMahabharatBook.test(new Book("Ramayan", "Valmiki"))); //false } } class Book { private String name; private String writer; public Book(String name, String writer) { this.name = name; this.writer = writer; } public String getName() { return name; } public String getWriter() { return writer; } public boolean equals(final Object obj) { if (obj == null) { return false; } final Book b = (Book) obj; if (this == b) { return true; } else { return (this.name.equals(b.name) && (this.writer == b.writer)); } } }
输出
---Testing Hello message---
true
false
---Testing Mahabharat book---
true
false
七、not(Predicate super T> target)
staticPredicate not(Predicate super T> target)
not
是Java 11
中引入的Predicate
的静态方法。
not
返回的predicate
是对所提供的predicate
的否定。
这是通过返回调用target.negate()
的结果来完成的。
找到Predicate.not
的例子。
PredicateNotDemo.java
import java.util.function.Predicate; public class PredicateNotDemo { public static void main(String[] args) { PredicateisOdd = n -> n % 2 == 1; Predicate isEven = Predicate.not(isOdd); System.out.println(isEven.test(10)); //true Predicate isNotHelloMsg = Predicate.not(Predicate.isEqual("Hello")); System.out.println(isNotHelloMsg.test("Hi")); //true System.out.println(isNotHelloMsg.test("Hello")); //false } }
输出
true
true
false
在Stream中使用Predicate
我们将提供例子在Stream
中使用Predicate
。
我们将使用Stream.filter
来过滤列表。
filter()
的语法如下。
filter(Predicate predicate)
filter()
在处理给定的Predicate
后,返回由过滤后的数据组成的Stream
实例。
例1:
PredicateStreamDemo1.java
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class PredicateStreamDemo1 { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add("Vijay"); list.add("Ramesh"); list.add("Mahesh"); Predicate isNameEndsWithSh = s -> s.endsWith("sh"); list.stream().filter(isNameEndsWithSh) .forEach(s -> System.out.println(s)); } }
输出
Ramesh
Mahesh
例2:
PredicateStreamDemo2.java
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class PredicateStreamDemo2 { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add(new Student("Mahesh", 20, "male", 38)); list.add(new Student("Gauri", 21, "female", 45)); list.add(new Student("Krishna", 19, "male", 42)); list.add(new Student("Radha", 20, "female", 35)); System.out.println("--- All students scoring marks > 40 ---"); Predicate isScoreGt40 = std -> std.getMarks() > 40; filterStudent(isScoreGt40, list).forEach(s -> System.out.println(s)); System.out.println("--- All Male Students ---"); Predicate isMaleStudent = std -> "male".equals(std.getGender()); filterStudent(isMaleStudent, list).forEach(s -> System.out.println(s)); System.out.println("--- All Female Students ---"); Predicate isFemaleStudent = std -> "female".equals(std.getGender()); filterStudent(isFemaleStudent, list).forEach(s -> System.out.println(s)); System.out.println("--- All Female Students scoring > 40 ---"); filterStudent(isFemaleStudent.and(isScoreGt40), list).forEach(s -> System.out.println(s)); } static List filterStudent(Predicate predicate, List list) { return list.stream().filter(predicate).collect(Collectors.toList()); } }
输出
--- All students scoring marks > 40 ---
Gauri - 21 - female - 45
Krishna - 19 - male - 42
--- All Male Students ---
Mahesh - 20 - male - 38
Krishna - 19 - male - 42
--- All Female Students ---
Gauri - 21 - female - 45
Radha - 20 - female - 35
--- All Female Students scoring > 40 ---
Gauri - 21 - female - 45
到此这篇关于浅谈Java8新特性Predicate接口的文章就介绍到这了,更多相关Java Predicate内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!