Function,BiFucntion理解与实例

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/83239465

    /**
     * 一个入参经过一个函数处理
      * @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
        res = (int)Function.identity().apply(4);
        System.out.println(res);//4

        /**
         * Returns a function that always returns its input argument.
         *
         * @param <T> the type of the input and output objects to the function
         * @return a function that always returns its input argument
         */
        static <T> Function<T, T> identity() {
            return t -> t;
        }

定义一个方法就可以实现多种功能,这就是前面说过的Lambda表达式传递的是一种行为

为什么BiFunction没有compose方法呢,大家仔细想一想,如果有compose方法的话,那就是先执行Function的apply方法,但是执行完毕后只返回一个参数,而BiFunction需要两个参数,所以肯定是不行的。

关于源码可自行查看

参考:https//www.jianshu.com/p/8dc46a2dc21d   Java8_Function和BiFunction

以上基于jdk1.8.131

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/83239465