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:
欢迎大家相互交流,相互学习
记得点个关注再走
閱讀更多 爪哇程序猿 的文章