java.util.function里提供了Predicate,Consumer和Function三个函数式接口
Predicate:T->boolean
Consumer:T->{}
Function:T->R
同时提供了多个针对原始类型操作的函数式接口
函数是接口 | 函数描述符 | 原始类型特化 |
Predicate<T> | T->boolean | IntPredicate,LongPredicate,DoublePredicate |
Consumer<T> | T->void | IntConsumer,LongConsumer,DoubleConsumer |
Function<T,R> | T->R | IntFunction<R>,IntToDoubleFunction,IntToLongFunction LongFunction<R>,LongToDoubleFunction,LongToIntFunction DoubleFunction<R>,DoubleToIntFunction,DoubleToLongFunction ToIntFunction<T>,ToLongFunction<T>,ToDoubleFunction<T> |
Supplier<T> | ()->T | BooleanSupplier,IntSupplier,LongSupplier,DoubleSupplier |
UnaryOperator<T> | T->T | IntUnaryOperator,LongUnaryOperator,DoubleUnaryOperator |
BinaryOperator<T> | (T,T)->T | IntBinaryOperator,LongBinaryOperator,DoubleBinaryOperator |
BiPredicate<L,R> | (L,R)->boolean | |
BiConsumer<T,U> | (T,U)->void | ObjIntConsumer<T>,ObjLongConsumer<T>,ObjDoubleConsumer<T> |
BiFunction<T,U,R> | (T,U)->R | ToIntBiFunction<T,U>,ToLongBiFunction<T,U>,ToDoubleBiFunction<T,U> |
比较器复合:
静态方法Comparator.comparing返回一个T->int, .reversed()反转排序,.thenComparing()二次排序
例如按苹果重量递减排序,重量一样得按国家排:
appleList.sort(comparing(Apple::getWeight)).reverse().thenComparing(Apple::getCountry)
谓词接口:
negate(非),or(或),and(与)
运算顺序看作与前面得结果运算,即a.or(b).and(c)=(a || b) && c
复合函数
andThen 和 compose 令Function<Integer,Integer> f = x -> x + 1;Function<Integer,Integer> g = x -> x * 2;
f.andThen(g):f的输出当作g的输入=g(f(x)) = (x+1)*2
f.compose(g): g的输出当作f的输入=f(g(x))=x*2+1
流只能forEach一次