Java8中的Predicate和Consumer

由于工作需求,最近了解了一下Java8中的Predicate和Consumer接口,在此浅谈一下对它们的理解和使用:

首先先来看一下Predicate官方文档解释:

直译:代表了对参数的断言(布尔值函数)。这是一个函数式接口,它的函数方法是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).

直译:表示一个接受单个输入参数并不返回结果的操作。与大多数其他函数式接口不同,Consumer期望通过 副作用操作。

          这是一个函数式接口,其功能方法是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();
	}
}
例子摘抄并发编程网, 点击打开链接
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值