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

249 阅读1分钟
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

测试结果:

result: 32
result: 64