源码
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
- apply( )
就是lambda中需要自己实现的抽象方法
栗子:
Function<Integer, Integer> function1 = x -> x * 2;
System.out.println(function1.apply(10));
输出的结果是 20
为了突出T和R,另一个栗子
Function<Integer, String> function3 = x -> x * 2 + " string ";
System.out.println(function3.apply(10));
输出的结果是 20 string
- compose()
是把两个function组合起来,首先执行compose中的function
Function<Integer, Integer> function1 = x -> x * 2;
System.out.println(function1.apply(10));
Function<Integer, String> function3 = x -> x * 2 + " string ";
System.out.println(function3.apply(10));
//这里把function1和function3 合起来了
System.out.println(function3.compose(function1).apply(10));
输出结果是
20
20 string
40 string
很明显,首先执行了compose里面的function1,然后再执行的function3。
-
andThen()
是把两个function组合起来,后执行andThen中的function
这个就不写示例了,正好是与compose()方法相反的。 -
identity()
返回一个方法,把参数原样输出
Function<Integer,Integer> function4=Function.identity();
System.out.println(function4.apply(10));
输出 10
说实话不知道这有啥用。。。