java 8 新特性之 Funtion & BiFunction

  • Function 接受一个参数 返回一个参数
  • BiFunction 接收两个参数 返回一个结果

Function

抽象方法

apply

1
R apply (T t)


1
2
3
4
5
int compute(int a, Function<Integer, Integer> function) {
return function.apply(a)
}

System.out.println(compute(3, a -> a + 8)) //11

default 方法

compose

1
2
3
<v> Function<V, R> compose(Function<? super V, ? extends T > before) {
return (V v) -> apply(before.apply(v));
}


1
2
3
4
5
6
int compute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(a);
}

System.out.println(3, a -> a + 8, b -> b * b) // 3 * 3 + 8 = 17
//先执行 function2 的 apply 再执行 function1 的 apply

andThen

1
2
3
<V> Function<T, V> andThen (Function<? super V, ? extends T> after) {
return (T t) -> after.apply((apply(t));
}


1
2
3
4
5
6
int compute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2 ) {
return function1.andThen(function2).apply(a);
}

System.out.println(3, a -> a + 8, b -> b * b) //(3 + 8) * (3 + 8) = 121
//先执行 function1 的 apply 再执行 function2 的 apply

BiFunction

抽象方法

apply

1
R apply(T t, U u);


1
2
3
4
5
int compute(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
return BiFunction.apply( a, b)
}

System.out.println(1, 2, (a, b) -> a + b) //3

default 方法

andThen

1
2
3
<V> BiFunction<T, U, V) andThen(Function<? super R, ? extends v> after) {
return (T t, U u) -> after.apply(apply(t, u));
}


1
2
3
4
int compute(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
return function.apply(biFunction.apply(a, b));
}
System.out.println(compute(2, 3, (a, b) -> a + b, c -> c * c)) // (2 + 3) * (2 + 3) = 25

------ end ------