Java 8中java.util.function包中的谓词和使用者接口
在我以前的文章中,我寫了關于Function接口的內容 ,它是java.util.package的一部分。 我還提到了Predicate接口,它是同一包的一部分,在這篇文章中,我將向您展示如何使用Predicate和Consumer接口。 讓我們看一下Javadoc for Predicate接口:
確定輸入對象是否符合某些條件。
在該接口中聲明/定義了5種方法(您一定想知道這是一個功能性接口 ,如果是,那么您必須在繼續之前閱讀此方法),這些方法是:
//Returns a predicate which evaluates to true only if this predicate //and the provided predicate both evaluate to true. and(Predicate<? super T> p)//Returns a predicate which negates the result of this predicate. negate()//Returns a predicate which evaluates to true if either //this predicate or the provided predicate evaluates to true or(Predicate<? super T> p)//Returns true if the input object matches some criteria test(T t)//Returns a predicate that evaluates to true if both or neither //of the component predicates evaluate to true xor(Predicate<? super T> p)除test(T t)以外的所有方法均為默認方法,而test(T t)為抽象方法。 提供此抽象方法實現的一種方法是使用匿名內部類,另一種方法是使用lambda表達式 。
用于消費者接口的Javadoc指出:
接受單個輸入參數且不返回結果的操作。 與大多數其他功能接口不同,消費者應該通過副作用來操作。
此接口中有2種方法,其中只有一種是抽象的,而該抽象方法是:accept(T t),它接受輸入并且不返回任何結果。 為了解釋有關謂詞和消費者界面的更多信息,我們考慮一個帶有名稱,等級和要支付費用的學生班。 每個學生都有一定的折扣,折扣取決于學生的成績。
class Student{String firstName;String lastName;Double grade;Double feeDiscount = 0.0;Double baseFee = 20000.0;public Student(String firstName, String lastName,Double grade) {this.firstName = firstName;this.lastName = lastName;this.grade = grade;}public void printFee(){Double newFee = baseFee - ((baseFee*feeDiscount)/100);System.out.println("The fee after discount: "+newFee);} }然后創建一個接受Student對象,謂詞實現和Consumer實現的方法。 如果您不熟悉Function界面,則應該花幾分鐘閱讀此內容 。 此方法使用謂詞來確定是否必須更新學生對費用的折扣,然后使用Consumer實現來更新折扣。
public class PreidcateConsumerDemo {public static Student updateStudentFee(Student student,Predicate<Student> predicate,Consumer<Student> consumer){//Use the predicate to decide when to update the discount.if ( predicate.test(student)){//Use the consumer to update the discount value.consumer.accept(student);}return student;}}謂詞和使用者中的測試方法和接受方法都分別接受聲明的泛型類型的參數。 兩者之間的區別在于謂詞使用參數來做出某些決定并返回布爾值,而Consumer使用參數來更改其某些值。 讓我們看一下如何調用updateStudentFee方法:
public static void main(String[] args) {Student student1 = new Student("Ashok","Kumar", 9.5);student1 = updateStudentFee(student1,//Lambda expression for Predicate interfacestudent -> student.grade > 8.5,//Lambda expression for Consumer inerfacestudent -> student.feeDiscount = 30.0);student1.printFee();Student student2 = new Student("Rajat","Verma", 8.0);student2 = updateStudentFee(student2,student -> student.grade >= 8,student -> student.feeDiscount = 20.0);student2.printFee();} 在這篇文章中,我通過示例解釋了如何利用謂詞和使用者接口,它們是Java 8中引入的java.util.function包的一部分。
翻譯自: https://www.javacodegeeks.com/2013/04/predicate-and-consumer-interface-in-java-util-function-package-in-java-8.html
總結
以上是生活随笔為你收集整理的Java 8中java.util.function包中的谓词和使用者接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么手机总是不能连接到FlashAir
- 下一篇: 重庆房价备案查询(重庆房价备案)