Lambda Consumer Predicate Supperlier Function
基本函数式接口
接口 | 参数 | 返回值 | 示例 |
---|---|---|---|
Consumer | T | void | s ->System.out.print(s) |
Predicate | T | boolean | s ->s.isEmpty() |
Supplier | 无参 | T | () -> new String() |
Function | T | U | s -> new Integer(s) |
● 原生特化:这些接口使用原生类型替换掉类型参数。代码
如下:
interface LongFunction { R apply(long value); }
interface ToIntFunction { intapplyAsInt(T value); }
interface LongToIntFunction { intapplyAsInt(long value); }
● Consumer、Predicate 与Function 的函数类型都接收单个
参数。有接收两个参数的相应接口,代码如下:
interface BiConsumer<T,U> { void accept(T t, U u); }
interface BiFunction<T,U,R> { R apply(T t,U u); }
interface ToIntBiFunction<T,U> { int apply(T t, U u); }
● Function 的常见用法要求其参数与结果拥有相同的类型。
之前在List.replaceAll 的参数中已经看到了这一点。我们
可以通过将Function 的变种特化为相应的Operator 来达
成所愿,如下所示:
interface UnaryOperator extends Function<T,T> { … }
interface BinaryOperator extends BiFunction<T,T,T> { … }
interface IntBinaryOperator { int applyAsInt(int left, int
right); }