函数式接口是单一抽象方法接口,@FunctionalInterface。
需要注意的是,函数式接口仍可定义普通方法与静态方法。
可能的函数式接口最多有四类:
- 有参数有返回值——功能性接口 Function
- 有参数无返回值——消费型接口 Consumer
- 无参数有返回值——供给型接口 Supplier
- 判断真假——断言型接口 Predicate
JAVA8 在 java.util.function 中提供了以下四个核心的函数式接口,来简化开发者的定义以及实现操作的统一。
需要注意的是,在函数式接口?
功能性接口 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);
}
消费型接口 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();
}
断言型接口 Predicate
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);
}
其他
- UnaryOperator
——接收 T 对象,返回 T 对象 - BinaryOperator
——接收两个 T 对象,返回 T 对象
除了上面的这些基本的函数式接口,我们还提供了一些针对原始类型(Primitive type)的特化(Specialization)函数式接口,例如 IntSupplier 和 LongBinaryOperator 。(我们只为 int 、 long 和 double 提供了特化函数式接口,如果需要使用其它原始类型则需要进行类型转换)同样的我们也提供了一些针对多个参数的函数式接口,例如 BiFunction