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

什么是函数式接口

更多参考: 定义:接口中只有一个抽象方法的接口。 函数式接口一般使用 @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 类型的结果。

更多参考:

经验分享 程序员 微信小程序 职场和发展