1. 程式人生 > >Function介面之andThen

Function介面之andThen

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執行