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

欢迎大家相互交流,相互学习

记得点个关注再走


分享到:


相關文章: