做那种事情的网站,中国月球空间站,重庆h5制作,网络推广外包公司在我以前的文章中#xff0c;我写了关于Function接口的内容 #xff0c;它是java.util.package的一部分。 我还提到了Predicate接口#xff0c;它是同一包的一部分#xff0c;在这篇文章中#xff0c;我将向您展示如何使用Predicate和Consumer接口。 让我们看一下Javadoc … 在我以前的文章中我写了关于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) 除testT t以外的所有方法均为默认方法而testT t为抽象方法。 提供此抽象方法实现的一种方法是使用匿名内部类另一种方法是使用lambda表达式 。 用于消费者接口的Javadoc指出 接受单个输入参数且不返回结果的操作。 与大多数其他功能接口不同消费者应该通过副作用来操作。 此接口中有2种方法其中只有一种是抽象的而该抽象方法是acceptT 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,PredicateStudent predicate,ConsumerStudent 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包的一部分。 参考来自JCG合作伙伴 Mohamed Sanaulla的Java 8中java.util.function包中的谓词和使用者接口来自Experiences Unlimited博客。 翻译自: https://www.javacodegeeks.com/2013/04/predicate-and-consumer-interface-in-java-util-function-package-in-java-8.html