java函数式编程之Consumer

java

参考https://blog.csdn.net/z345434645/article/details/53794724

  https://blog.csdn.net/chuji2012/article/details/77871011

1、先来看一个简单的Consumer<T>的例子

描述:Consumer< T>接口接受一个T类型参数,没有返回值。

源码如下:

public interface Consumer<T> {

/**

* Performs this operation on the given argument.

*

* @param t the input argument

*/

void accept(T t);

}

测试代码如下:

@Test

public void test(){

UserT userT = new UserT("zm");

//接受一个参数

Consumer<UserT> userTConsumer = userT1 -> userT1.setName("zmChange");};

userTConsumer.accept(userT);

logger.info(userT.getName());//输出zmChange

}

java8以前的实现如下:

@Test

public void test1(){

UserT userT = new UserT("zm");

this.change(userT);

logger.info(userT.getName());//输出zmChange

}

private void change(UserT userT){

userT.setName("zmChange");

}

2、Predicate和Consumer综合应用

为了详细说明Predicate和Consumer接口,通过一个学生例子:Student类包含姓名、分数以及待付费用,每个学生可根据分数获得不同程度的费用折扣。

Student类源代码:

public class Student {

String firstName;

String lastName;

Double grade;

Double feeDiscount = 0.0;

Double baseFee = 2000.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对象的Predicate接口以及Consumer接口的实现类。本例子使用Predicate接口实现类的test()方法判断输入的Student对象是否拥有费用打折的资格,然后使用Consumer接口的实现类更新输入的Student对象的折扣。

public class PredicateConsumerDemo {

public static Student updateStudentFee(Student student, Predicate<Student> predicate, Consumer<Student> consumer){

if (predicate.test(student)){

consumer.accept(student);

}

return student;

}

}

Predicate和Consumer接口的test()和accept()方法都接受一个泛型参数。不同的是test()方法进行某些逻辑判断并返回一个boolean值,而accept()接受并改变某个对象的内部值。updateStudentFee方法的调用如下所示:

public class Test {

public static void main(String[] args) {

Student student1 = new Student("Ashok","Kumar", 9.5);

student1 = updateStudentFee(student1,

//Lambda expression for Predicate interface

student -> student.grade > 8.5,

//Lambda expression for Consumer inerface

student -> student.feeDiscount = 30.0);

student1.printFee(); //The fee after discount: 1400.0

Student student2 = new Student("Rajat","Verma", 8.0);

student2 = updateStudentFee(student2,

//Lambda expression for Predicate interface

student -> student.grade >= 8,

//Lambda expression for Consumer inerface

student -> student.feeDiscount = 20.0);

student2.printFee();//The fee after discount: 1600.0

}

}

以上是 java函数式编程之Consumer 的全部内容, 来源链接: utcz.com/z/390787.html

回到顶部