01.02 java8 學習Lambda <第三天> Function接口

Function接口:

源碼截圖如下:


java8 學習Lambda <第三天> Function接口

Function接口類 源碼

<code>//Function倆個function嵌套 

/**
* default Function 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
}

/**
* default Function 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>
/<integer>/<integer>
/<code>
<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接口 函數會接收2個參數得到一個結果 Function接口的一種特化形式

<code>//BiFunction
/**
* BiFunction接口 函數會接收2個參數得到一個結果 Function接口的一種特化形式
* 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>
<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源碼:

java8 學習Lambda <第三天> Function接口

BiFunction源碼

<code>/**
* default BiFunction 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>
<code>System.out.println(test06.compute(1,2,(value1,value2)->value1+value2,value->value*2));
/<code>


Demo:


java8 學習Lambda <第三天> Function接口

Demo

歡迎大家相互交流,相互學習

記得點個關注再走


分享到:


相關文章: