Function 是一个函数式接口,andThen它的一个默认方法,就是在Function1执行后执行Function2。
源码:
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
代码:
Function<Integer, Integer> first=x ->x*x;
Function<Integer, Integer> after=y->y*2;
System.out.println(first.apply(3));
System.out.println(after.apply(3));
int res=first.andThen(after).apply(4);
System.out.println(res);
显示结果:
9
6
32
分析:
1.Function1-first 计算一个数的平方,3的平方9
2.Function2-after 计算一个数的2倍,3的两倍6
4.Function1.andThen 先是4的平方16,再16的2倍32.
结论:
f1.andThen(f2).apply(arg) f1执行后,f2执行