函数式接口总结
函数式接口总结
四大核心接口
| 接口 | 方法签名 | 用途 | 示例 |
|---|---|---|---|
| Function<T, R> | R apply(T t) | 转换型,输入 T 返回 R | Function<String, Integer> f = String::length; |
| Consumer | void accept(T t) | 消费型,只进不出 | Consumer<String> c = System.out::println; |
| Supplier | T get() | 供给型,只出不进 | Supplier<Double> s = Math::random; |
| Predicate | boolean test(T t) | 断言型,返回布尔值 | Predicate<String> p = String::isEmpty; |
分类速查
Function 系(转换型,有输入有输出)
| 接口 | 输入 | 输出 | 特有方法 |
|---|---|---|---|
Function<T,R> | T | R | andThen,compose,identity() |
BiFunction<T,U,R> | T, U | R | andThen |
UnaryOperator<T> | T | T | 继承 Function,identity() |
BinaryOperator<T> | T, T | T | 继承 BiFunction,minBy,maxBy |
IntFunction<R> | int | R | apply |
LongFunction<R> | long | R | apply |
DoubleFunction<R> | double | R | apply |
ToIntFunction<T> | T | int | applyAsInt |
ToLongFunction<T> | T | long | applyAsLong |
ToDoubleFunction<T> | T | double | applyAsDouble |
IntToLongFunction | int | long | applyAsLong |
IntToDoubleFunction | int | double | applyAsDouble |
LongToIntFunction | long | int | applyAsInt |
LongToDoubleFunction | long | double | applyAsDouble |
DoubleToIntFunction | double | int | applyAsInt |
DoubleToLongFunction | double | long | applyAsLong |
ToIntBiFunction<T,U> | T, U | int | applyAsInt |
ToLongBiFunction<T,U> | T, U | long | applyAsLong |
ToDoubleBiFunction<T,U> | T, U | double | applyAsDouble |
Consumer 系(消费型,有输入无输出)
| 接口 | 输入 | 特有方法 |
|---|---|---|
Consumer<T> | T | andThen,accept |
BiConsumer<T,U> | T, U | andThen,accept |
IntConsumer | int | andThen,accept |
LongConsumer | long | andThen,accept |
DoubleConsumer | double | andThen,accept |
ObjIntConsumer<T> | T, int | accept |
ObjLongConsumer<T> | T, long | accept |
ObjDoubleConsumer<T> | T, double | accept |
###Supplier 系(供给型,无输入有输出)
| 接口 | 输出 | 示例 |
|---|---|---|
Supplier<T> | T | () -> new User() |
BooleanSupplier | boolean | () -> true |
IntSupplier | int | () -> 42 |
LongSupplier | long | System::currentTimeMillis |
DoubleSupplier | double | Math::random |
Predicate 系(断言型,返回 boolean)
| 接口 | 输入 | 特有方法 |
|---|---|---|
Predicate<T> | T | and,or,negate,isEqual |
BiPredicate<T,U> | T, U | and,or,negate |
IntPredicate | int | and,or,negate |
LongPredicate | long | and,or,negate |
DoublePredicate | double | and,or,negate |
命名规律速记
| 前缀/后缀 | 含义 | 示例 |
|---|---|---|
Bi | 两个参数 | BiFunction,BiConsumer,BiPredicate |
Unary | 一元,输入输出同类型 | UnaryOperator<T>即Function<T,T> |
Binary | 二元,输入输出同类型 | BinaryOperator<T>即BiFunction<T,T,T> |
ToInt/ToLong/ToDouble | 返回基本类型 | ToIntFunction<T> |
Int/Long/Double前缀 | 参数是基本类型 | IntFunction<R>,IntConsumer |
Obj+ 基本类型 | 对象 + 基本类型参数 | ObjIntConsumer<T> |
