函数式接口是单一抽象方法接口,@FunctionalInterface。
需要注意的是,函数式接口仍可定义普通方法与静态方法

可能的函数式接口最多有四类:

  • 有参数有返回值——功能性接口 Function
  • 有参数无返回值——消费型接口 Consumer
  • 无参数有返回值——供给型接口 Supplier
  • 判断真假——断言型接口 Predicate

JAVA8 在 java.util.function 中提供了以下四个核心的函数式接口,简化开发者的定义以及实现操作的统一
需要注意的是,在函数式接口?

功能性接口 Function

  1. @FunctionalInterface
  2. public interface Function<T, R> {
  3. /**
  4. * Applies this function to the given argument.
  5. *
  6. * @param t the function argument
  7. * @return the function result
  8. */
  9. R apply(T t);
  10. }

消费型接口 Consumer

  1. @FunctionalInterface
  2. public interface Consumer<T> {
  3. /**
  4. * Performs this operation on the given argument.
  5. *
  6. * @param t the input argument
  7. */
  8. void accept(T t);
  9. }

供给型接口 Supplier

  1. @FunctionalInterface
  2. public interface Supplier<T> {
  3. /**
  4. * Gets a result.
  5. *
  6. * @return a result
  7. */
  8. T get();
  9. }

断言型接口 Predicate

  1. public interface Predicate<T> {
  2. /**
  3. * Evaluates this predicate on the given argument.
  4. *
  5. * @param t the input argument
  6. * @return {@code true} if the input argument matches the predicate,
  7. * otherwise {@code false}
  8. */
  9. boolean test(T t);
  10. }

其他

  • UnaryOperator——接收 T 对象,返回 T 对象
  • BinaryOperator——接收两个 T 对象,返回 T 对象

除了上面的这些基本的函数式接口,我们还提供了一些针对原始类型(Primitive type)的特化(Specialization)函数式接口,例如 IntSupplier 和 LongBinaryOperator 。(我们只为 int 、 long 和 double 提供了特化函数式接口,如果需要使用其它原始类型则需要进行类型转换)同样的我们也提供了一些针对多个参数的函数式接口,例如 BiFunction ,它接收 T 对象和 U 对象,返回 R 对象。