Java 8 特性-函数式接口详解

什么是函数式接口

更多参考:https://www.yuque.com/zhangshuaiyin/java/java-8-function-interface
定义:接口中只有一个抽象方法的接口。
函数式接口一般使用 @FunctionalInterface 注解修饰,目的是检查接口是否符合函数式接口规范。
注意点:

  • 函数式接口中可以有 默认方法 和静态方法
  • 函数式接口重写父类的方法,并不会计入到自己的抽象方法中

Java 8 内置了 4 个常用的函数式接口

  • Consumer 消费型接口:接受一个参数并进行逻辑操作,无返回值;
  • Supplier 供给型接口:不接受参数,操作后返回一个对象;
  • Function<T, R> 函数型接口:接收一个泛型T对象,操作后返回泛型R对象;
  • Predicate 断言型接口:接收一个参数,操作后返回一个 boolean 值;

Consumer

接口定义:

@FunctionalInterface
public interface Consumer<T> {

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

消费型接口:接收一个参数进行处理,不返回结果。

Supplier

接口定义:

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

供给型接口:不接受参数,返回一个泛型类型的对象;

如何使用:使用时提供该接口的实现,并返回一个泛型类型的对象;

Function

接口定义:

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}

函数型接口:提供一个 T 类型的参数,返回一个 R 类型的结果。

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);
}

断言型接口:输入一个 T 类型的参数,返回 boolean 类型的结果。

更多参考:https://www.yuque.com/zhangshuaiyin/java/java-8-function-interface

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值