1 Function<T, R>中的T, R表示接口輸入、輸出的數據類型。
-
R apply(T t)
- apply:
-
.例子:
func是定義好的Function接口類型的變量,他的輸入、輸出都是Integer類型,調用calculate方法時,將func作為參數傳入,對參數5進行處理。FunctionTest functionTest = new FunctionTest();
// return e + 5;就是apply方法的具體實現
Function<Integer, String> func = e -> {return String.valueOf(e + 6);};
String result = functionTest.calculate(5, func);
System.out.println(result);
public String calculate(Integer a, Function<Integer, String> function) {
return function.apply(a);
} -
andThen:
- 先處理參數,再對返回值使用
操作after進行處理。
Function<Integer, Integer> func = e -> {return e + 5;};
Function<Integer, Integer> func2 = e -> {return e * 5;};
//func2即after
func.andThen(func2).apply(5); // 50
compose:
- 和
andThen剛好相反:先使用操作before處理參數,再對返回值進行處理。
Function<Integer, Integer> func = e -> {return e + 5;};
Function<Integer, Integer> func2 = e -> {return e * 5;};
//func2即before
func.compose(func2).apply(5); // 30 -
compose源碼:
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));//第一個apply是調用當前接口的方法
} - 注意
compose方法的返回值依然是Function<T, R>類型,所以不是
return this.apply(before.apply(v));
案例: - 先處理參數,再對返回值使用
-
public class FunctionTest2 { public static void main(String[] args) { FunctionTest2 functionTest2 = new FunctionTest2(); int result1 = functionTest2.compute(5, e -> e * 5, e -> e + 5); int result2 = functionTest2.compute2(5, e -> e * 5, e -> e + 5); int result3 = functionTest2.compute3(5, e -> e * 5, e -> e + 5); int result4 = functionTest2.compute4(5, e -> e * 5, e -> e + 5); System.out.println(result1);//50 System.out.println(result2);//30 System.out.println(result3);//130 System.out.println(result4);//250 }public int compute(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(source);
}
public int compute2(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(source);
}
public int compute3(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).compose(function1).apply(source); //從后往前 25 125 130
}
public int compute4(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).andThen(function1).apply(source); } //10*5 50*5
}
