0%

functional-interface

函数式接口也称为 SAM 接口(Single Abstract Method Interface)

其特点是:

  • 有且仅有一个抽象方法
  • 允许定义静态方法
  • 允许定义默认方法
  • 可以使用 @FunctionalInterface 注解修饰, 方便编译器检查, 但不是必须的

1. 主要接口

  • Consumer
1
2
3
4
// 消费对象
void accept(T t)
// 再次消费对象
default Consumer<T> andThen(Consumer<? super T> after)
  • Function
1
2
3
4
5
6
7
8
// 转换对象
R apply(T t);
// 前置处理
default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
// 后置处理
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
// 原封返回传入对象
static <T> Function<T, T> identity()
  • Predicate
1
2
3
4
5
6
7
8
// 断言对象
boolean test(T t);
// 与
default Predicate<T> and(Predicate<? super T> other)
// 非
default Predicate<T> negate()
// 或
default Predicate<T> or(Predicate<? super T> other)
  • Supplier
1
2
// 提供对象
T get();

2. Resource