且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 8里一元函数Function的compose和andThen方法区别

更新时间:2022-09-11 18:11:26

Function<Integer, Integer> times2 = e -> e * 2;

        Function<Integer, Integer> squared = e -> e * e;

        // 先执行参数,再执行调用者
        /*
         * 1. 4 * 4 = 16 16 * 2 = 32
         */
        System.out.println("result: " + times2.compose(squared).apply(4)); // 32

        /*
         * 先执行调用者: 4 * 2 = 8 再执行then传入的function 8 * 8 = 64
         */
        System.out.println("result: " + times2.andThen(squared).apply(4)); // 64

Java 8里一元函数Function的compose和andThen方法区别