5. 函数式接口

5.1 概述

只有一个抽象方法的接口我们称之为函数接口。

JDK的函数式接口都加上了@FunctionalInterface (与重写方法的注解作用类似,校验作用) 注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。

 

5.2 常见函数式接口

  • Consumer 消费接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。

     

     

  • Function 计算转换接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回

     

     

  • Predicate 判断接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果

     

     

  • Supplier 生产型接口

    根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回

 

 

 

5.3 常用的默认方法

  • and

    我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件

    例如:

    打印作家中年龄大于17并且姓名的长度大于1的作家。

             List<Author> authors = getAuthors();
             Stream<Author> authorStream = authors.stream();
             authorStream.filter(new Predicate<Author>() {
                 @Override
                 public boolean test(Author author) {
                     return author.getAge()>17;
                }
            }.and(new Predicate<Author>() {
                 @Override
                 public boolean test(Author author) {
                     return author.getName().length()>1;
                }
            })).forEach(author -> System.out.println(author));
  • or

    我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。

    例如:

    打印作家中年龄大于17或者姓名的长度小于2的作家。

     //        打印作家中年龄大于17或者姓名的长度小于2的作家。
             List<Author> authors = getAuthors();
             authors.stream()
                    .filter(new Predicate<Author>() {
                         @Override
                         public boolean test(Author author) {
                             return author.getAge()>17;
                        }
                    }.or(new Predicate<Author>() {
                         @Override
                         public boolean test(Author author) {
                             return author.getName().length()<2;
                        }
                    })).forEach(author -> System.out.println(author.getName()));

     

  • negate

    Predicate接口中的方法。negate方法相当于是在判断添加前面加了个! 表示取反

    例如:

    打印作家中年龄不大于17的作家。

     //        打印作家中年龄不大于17的作家。
             List<Author> authors = getAuthors();
             authors.stream()
                    .filter(new Predicate<Author>() {
                         @Override
                         public boolean test(Author author) {
                             return author.getAge()>17;
                        }
                    }.negate()).forEach(author -> System.out.println(author.getAge()));
  •  

原文地址:http://www.cnblogs.com/shanzha/p/16880269.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性