0%

函数式接口

  • 只有一个抽象方法的接口我们称之为函数式接口
    • JDK 的函数式接口都加上了 @Functionallnterface 注解进行标识。但是无论是否加上该注解,只要接口中只有一个抽象方法,都是函数式接口。

4.函数式接口

4.1 概述

  • 只有一个抽象方法的接口我们称之为函数式接口
    • JDK 的函数式接口都加上了 @Functionallnterface 注解进行标识。但是无论是否加上该注解,只要接口中只有一个抽象方法,都是函数式接口。

4.2 常见的函数式接口

Predicate判断接口

  • 在 Predicate 判断接口中,我们可以在 test 方法中对传入的参数进行条件判断,返回判断结果。

    1
    2
    3
    4
    5
    6
    7
    @FunctionalInterface
    public interface Predicate<T> {

    boolean test(T t); // 抽象方法test

    ......
    }
  • 在 Stream 流的 filter 方法中,就用到了 Predicate 接口。

Consumer消费接口

  • 在 Consumer 消费接口中,我们可以在 accept 方法中对传入的参数进行消费处理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @FunctionalInterface
    public interface Consumer<T> {

    void accept(T t); // 抽象方法accept

    default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
    }
    }
  • 在 Stream 流的 forEach 方法中,就用到了 Consumer 接口。

Function计算转换接口

  • 在 Function 计算转换接口中,我们可以在 apply 方法中对传入的参数进行计算或转换,把结果返回。

    1
    2
    3
    4
    5
    6
    public interface Function<T, R> {

    R apply(T t); // 抽象方法apply

    ......
    }
  • 在 Stream 流的 mapflatMap 方法中,就用到了 Function 接口。

Supplier生产型接口

  • 在 Supplier 生产型接口中,我们可以在 get 方法中创建对象,把创建好的对象返回。

    1
    2
    3
    4
    5
    @FunctionalInterface
    public interface Supplier<T> {

    T get(); // 抽象方法get
    }
  • 在 Optional 类的 orElseGetorElseThrow 方法中,就用到了 Supplier 生产型接口。

4.3 函数式接口常用的默认方法(不重要)

and

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

or

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

negate

  • Predicate 接口中的方法。negate 方法相当于是在判断条件前面加了个 ! 表示取反。
---------------The End---------------