由于工作需求,最近了解了一下Java8中的Predicate和Consumer接口,在此浅谈一下对它们的理解和使用:
首先先来看一下Predicate官方文档解释:
-
Represents a predicate (boolean-valued function) of one argument.
This is a functional interface whose functional method is
test(Object)
.
直译:代表了对参数的断言(布尔值函数)。这是一个函数式接口,它的函数方法是test(Object).
这句话不是很好理解,我解释一下,Predicate翻译过来是“断言”、“断定”的意思,就是说它是会对输入参数进行判断,然后返回布尔值;这是一个函数式接口,通过它的test(Object)方法返回布尔值结果,关于什么是函数式接口,可自行Google或百度,不影响对其的理解,在此不作深究。
再看一下Consumer官方文档解释:
-
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces,
Consumer
is expected to operate via side-effects.This is a functional interface whose functional method is
accept(Object)
.
这是一个函数式接口,其功能方法是accept(Object)。
这里有一个关键词:side-effects,翻译过来是副作用,它指的是函数或表达式修改基本变量的行为,例如有两个int类型的变量x和y,x+y只是返回相加的结果,并没有改变x和y的值,那么这个操作就没有副作用;而赋值操作如x=1,由于将1赋值给x,改变了x的值,因此这个操作具有副作用。
简单来说就是Consumer接口并不返回任何值,而只是接收参数并将他们的状态通过副作用改变(其实就是个赋值操作)。
这里有一个很好的例子来展示这两个接口的使用场景:
例如对学生而言,Student类包含姓名,分数以及待付费用,每个学生可根据分数获得不同程度的费用折扣。
public 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);
}
}
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.junit.Test;
public class PredicateConsumerDemo {
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;
}
@Test
public void test() {
Student student1 = new Student("Ashok", "Kumar", 9.5);
student1 = updateStudentFee(student1, new Predicate<Student>() {
@Override
public boolean test(Student t) {
return t.grade > 8.5;
}
}, new Consumer<Student>() {
@Override
public void accept(Student t) {
t.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();
}
}
例子摘抄并发编程网,
点击打开链接。