Java Predicate及Consumer接口函数代码实现解析

 更新时间:2020年06月08日 11:29:11   作者:笨拙的小菜鸟  
这篇文章主要介绍了Java Predicate及Consumer接口函数代码实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Predicate函数编程

Predicate功能判断输入的对象是否符合某个条件。官方文档解释到:Determines if the input object matches some criteria.

了解Predicate接口作用后,在学习Predicate函数编程前,先看一下Java 8关于Predicate的源码:

@FunctionalInterface
public interface Predicate<T> {

  /**
   * Evaluates this predicate on the given argument.
   *
   * @param t the input argument
   * @return {@code true} if the input argument matches the predicate,
   * otherwise {@code false}
   */
  boolean test(T t);

  default Predicate<T> and(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) && other.test(t);
  }

  default Predicate<T> negate() {
    return (t) -> !test(t);
  }

  default Predicate<T> or(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) || other.test(t);
  }


  static <T> Predicate<T> isEqual(Object targetRef) {
    return (null == targetRef)
        ? Objects::isNull
        : object -> targetRef.equals(object);
  }
}

从上面代码可以发现,Java 8新增了接口的默认(default)方法和(static)静态方法。在Java 8以前,接口里的方法要求全部是抽象方法。但是静态(static)方法只能通过接口名调用,不可以通过实现类的类名或者实现类的对象调用;默认(default)方法只能通过接口实现类的对象来调用。

接下来主要来使用接口方法test,可以使用匿名内部类提供test()方法的实现,也可以使用lambda表达式实现test()。
体验一下Predicate的函数式编程,使用lambda实现。其测试代码如下:

@Test
public void testPredicate(){
  java.util.function.Predicate<Integer> boolValue = x -> x > 5;
  System.out.println(boolValue.test(1));//false
  System.out.println(boolValue.test(6));//true
}

第1行代码:定义一个Predicate实现,入参为Integer,返回传入参数与5做比较。
第2,3行代码调用第一行,传入相关参数。

Consumer函数编程

Consumer接口的文档声明如下:

An operation which accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

即接口表示一个接受单个输入参数并且没有返回值的操作。不像其它函数式接口,Consumer接口期望执行带有副作用的操作(Consumer的操作可能会更改输入参数的内部状态)。

同样,在了解Consumer函数编程前,看一下Consumer源代码,其源代码如下:

@FunctionalInterface
public interface Consumer<T> {

  /**
   * Performs this operation on the given argument.
   *
   * @param t the input argument
   */
  void accept(T t);

  /**
   * Returns a composed {@code Consumer} that performs, in sequence, this
   * operation followed by the {@code after} operation. If performing either
   * operation throws an exception, it is relayed to the caller of the
   * composed operation. If performing this operation throws an exception,
   * the {@code after} operation will not be performed.
   *
   * @param after the operation to perform after this operation
   * @return a composed {@code Consumer} that performs in sequence this
   * operation followed by the {@code after} operation
   * @throws NullPointerException if {@code after} is null
   */
  default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
  }
}

从上面代码可以看出,Consumer使用了Java 8接口新特性——接口默认(default)方法。接下来使用接口方法accept,体验一下Consumer函数编程。其测试代码如下:

@Test
public void testConsumer(){
  User user = new User("zm");
  //接受一个参数
  Consumer<User> userConsumer = User1 -> User1.setName("zmChange");
  userConsumer.accept(user);
  System.out.println(user.getName());//zmChange
}

在Java 8之前的实现如下:

@Test
public void test(){
  User user = new User("zm");
  this.change(user);
  System.out.println(user.getName());//输出zmChange
}

private void change(User user){
  user.setName("zmChange");
}

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

  }
}

通过简单对Predicate接口和Consumer接口进行应用,对函数式编程有了一个直观认识。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java使用POI-TL实现生成有个性的简历

    Java使用POI-TL实现生成有个性的简历

    POI-TL 是一个基于 Apache POI 的 Java 库,专注于在 Microsoft Word 文档(.docx 格式)中进行模板填充和动态内容生成,下面我们看看如何使用POI-TL生成有个性的简历吧
    2024-11-11
  • 如何通过一个注解实现MyBatis字段加解密

    如何通过一个注解实现MyBatis字段加解密

    用户隐私很重要,因此很多公司开始做数据加减密改造,下面这篇文章主要给大家介绍了关于如何通过一个注解实现MyBatis字段加解密的相关资料,需要的朋友可以参考下
    2022-02-02
  • SpringMVC项目异常处理机制详解

    SpringMVC项目异常处理机制详解

    SpringMVC是一种基于Java,实现了Web MVC设计模式,请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将Web层进行职责解耦。基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,SpringMVC也是要简化我们日常Web开发
    2022-08-08
  • Maven基础知识大梳理

    Maven基础知识大梳理

    这篇文章主要是Maven基础知识大梳理,Maven主要是用来解决导入java类依赖的jar,编译java项目主要问题,大家可以读一读这篇文章,更深一步的了解Maven
    2021-08-08
  • Spring Security实现自动登陆功能示例

    Spring Security实现自动登陆功能示例

    自动登录在很多网站和APP上都能用的到,解决了用户每次输入账号密码的麻烦。本文就使用Spring Security实现自动登陆功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • 详解MyBatis中column属性的总结

    详解MyBatis中column属性的总结

    在MyBatis的映射中有column这么一个属性,我一直以为它映射的是数据库表中的列名,但经过学习发现他似乎映射的是SQL语句中的列名,或者说是查询结果所得到的表的列名,这篇文章主要介绍了MyBatis中column属性的总结,需要的朋友可以参考下
    2022-09-09
  • HashMap每次扩容为什么是2倍

    HashMap每次扩容为什么是2倍

    当HashMap在初始化没有指定容量的情况下,首次添加元素时,数组的容量为16;当超出阈值,数组容量为扩容为之前的2倍,为什么HashMap每次扩容都是之前的2倍?下面就介绍一下
    2024-11-11
  • MyBatis实现简单的数据表分月存储

    MyBatis实现简单的数据表分月存储

    本文主要介绍了MyBatis实现简单的数据表分月存储,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • Maven项目中读取src/main/resources目录下的配置文件的方法

    Maven项目中读取src/main/resources目录下的配置文件的方法

    本篇文章主要介绍了Maven项目中读取src/main/resources目录下的配置文件的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • java 缓冲流的概念使用方法以及实例详解

    java 缓冲流的概念使用方法以及实例详解

    这篇文章主要为大家介绍了java 缓冲流的概念使用方法以及实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06

最新评论