Function接口:
源碼截圖如下:
<code>//Function倆個function嵌套
/**
* defaultFunction /<code>compose(Function super V, ? extends T> before) {
* Objects.requireNonNull(before);
* return (V v) -> apply(before.apply(v));
* }
* compose先應用參數的apply方法 先執行func2的apply 2*2 作為參數執行func1的apply 2*2*3
*/
public int compute(int a, Function<integer> func1, Function<integer> func2){
return func1.compose(func2).apply(a); //12
}
/**
* defaultFunction /<integer>/<integer>andThen(Function super R, ? extends V> after) {
* Objects.requireNonNull(after);
* return (T t) -> after.apply(apply(t));
* }
* andThen 先應用當前對象apply方法 先執行func1的apply 2*3 作為參數執行func1的apply (2*3)*(2*3)
*/
public int compute2(int a, Function<integer> func1, Function<integer> func2){
return func1.andThen(func2).apply(a); //36
}/<integer>/<integer>
<code>Test06 test06 = new Test06();
System.out.println(test06.compute(2,value->value*3,value->value*value)); //12
System.out.println(test06.compute2(2,value->value*3,value->value*value)); //36/<code>
//BiFunction
如果想動態傳入2個值 很明顯Function不支持 這時候會有BiFunction接口
BiFunction
<code>//BiFunction
/**
* BiFunction接口 函數會接收2個參數得到一個結果 Function接口的一種特化形式 /<code>
* R apply(T t,U u);
*/
public int add(int a,int b){
return a+b;
}
public int compute(int a,int b,BiFunction<integer> func){
return func.apply(a,b);
}
/<integer>
<code>//BiFunction
System.out.println(test06.compute(1,2,(value1,value2)->value1+value2));
System.out.println(test06.compute(1,2,(value1,value2)->value1*value2));/<code>
biFunction源碼:
<code>/**
* defaultBiFunction /<code>andThen(Function super R, ? extends V> after) {
* Objects.requireNonNull(after);
* return (T t, U u) -> after.apply(apply(t, u));
* }
* System.out.println(test06.compute(1,2,(value1,value2)->value1+value2,value->value*2));
* 1+2=3 把3當成function的輸入計算3*2 = 6
*/
public int compute(int a,int b,BiFunction<integer> func1,Function<integer> func2){
return func1.andThen(func2).apply(a,b);
}
}/<integer>/<integer>
<code>System.out.println(test06.compute(1,2,(value1,value2)->value1+value2,value->value*2));
/<code>
Demo:
歡迎大家相互交流,相互學習
記得點個關注再走
閱讀更多 爪哇程序猿 的文章