1. 程式人生 > >Function,BiFucntion理解與例項

Function,BiFucntion理解與例項


    /**
     * 一個入參經過一個函式處理
      * @param a
     * @param function
     * @return
     */
    public int computeApply(int a, Function<Integer, Integer> function) {
        int result = function.apply(a);
        return result;
    }

    /**
     * 一個入參經過兩個函式處理
     * @param a
     * @param function1
     * @param function2
     * @return
     */
    public int computeCompose(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
        return function1.compose(function2).apply(a);
    }

    /**
     * 一個入參經過兩個函式處理
     * @param a
     * @param function1
     * @param function2
     * @return
     */
    public int computeAddThen(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
        return function1.andThen(function2).apply(a);
    }


    /**
     * 兩個入參經過兩個函式處理,使用BiFunction
     * @param a
     * @param b
     * @param function1
     * @param function2
     * @return
     */
    public int computeBiFunctionAddThen(int a, int b, BiFunction<Integer, Integer, Integer> function1, Function<Integer, Integer> function2) {
        return function1.andThen(function2).apply(a, b);
    }
  Main test = new Main();
        int res;
        res = test.computeApply(5, value -> value * value);
        System.out.println(res);//25
        res = test.computeApply(5, value -> value + value);
        System.out.println(res);//10
        res = test.computeApply(5, value -> value - 2);
        System.out.println(res);//3

        res = test.computeCompose(2, value -> value * 3, value -> value * value);//後面的函式先計算
        System.out.println(res);//12

        res = test.computeAddThen(2, value -> value * 3, value -> value * value);//前面的函式先計算
        System.out.println(res);//36

        res = test.computeBiFunctionAddThen(2, 3, (a, b) -> a + b, value -> value * value);//前面的函式先計算
        System.out.println(res);//25

定義一個方法就可以實現多種功能,這就是前面說過的Lambda表示式傳遞的是一種行為

為什麼BiFunction沒有compose方法呢,大家仔細想一想,如果有compose方法的話,那就是先執行Function的apply方法,但是執行完畢後只返回一個引數,而BiFunction需要兩個引數,所以肯定是不行的。

關於原始碼可自行檢視

以上基於jdk1.8.131