java8系列04——函数式接口

1 函数式接口概述

只有一个抽象方法的接口。@FunctionInterface可以用来标注一个函数式接口,当然,这个注解并不是函数式接口的必要条件。它仅仅是用来进行标注、校验。比如一个接口标注了FunctionInterface,当它没有抽象方法,或者有多个抽象方法,都会爆红。

image-20220304201550381

2 常见函数式接口
2.1 Consumer

对传入的参数进行消费。

image-20220304201900377

2.2 Function

对传入的参数进行计算或转换。

image-20220304202052896

2.3 Predicate

判断型接口。

image-20220304202214955

2.4 Supplier

生产型接口。我们可以在方法中创建对象,并返回。

image-20220304202424947

3 常用的默认方法
3.1 and

我们在使用predicate接口时,可能需要进行判断条件的拼接。

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

例:打印作家中年龄小于18并且姓名长度大于1的作家。

  private static void test34() {
        getAuthors().stream().
                filter((new Predicate<Author>() {
                    @Override
                    public boolean test(Author author) {
                        return author.getAge() < 18;
                    }
                }).and(new Predicate<Author>() {
                            @Override
                            public boolean test(Author author) {
                                return author.getName().length() > 1;
                            }
                        }))
                .forEach(author -> System.out.println(author.getName() + ": " + author.getAge()));
    }

将其转换为lambda表达式并不优雅,读者可以自行尝试。

我们可以自己使用&&达到同样效果。

 private static void test34() {
        getAuthors().stream().
                filter(author -> author.getAge() < 18 && author.getName().length() > 1)
                .forEach(author -> System.out.println(author.getName() + ": " + author.getAge()));
    }

您是不是认为这个and方法优点鸡肋,你错了,因为它的使用场景并非如此。举例如下。

  private static void test35() {
        printNum(value -> value % 2 == 0, value -> value > 5);
    }

    public static void printNum(IntPredicate predicate1, IntPredicate predicate2) {
        int [] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int num : arr) {
            if(predicate1.and(predicate2).test(num)) {
                System.out.println(num);
            }
        }
    }
3.2 Or

例:打印年龄大于17或者小于15的作家。

private static void test36() {
        getAuthors().stream()
                .filter(((Predicate<Author>) author -> author.getAge() > 17).or(author -> author.getAge() < 15)
                ).forEach(System.out::println);
}
3.3 negate

例:打印名字不叫小米的作家。

  private static void test37() {
        getAuthors().stream()
                .filter(((Predicate<Author>) author -> author.getName().equals("小米")).negate()).forEach(System.out::println);
    }

以上几个方法一般都是在自定义函数式接口中使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半旧518

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值