java中BiFunction和Function詳解
關於Lambda詳見lambda描述。關於函式式介面詳見函式式介面
首先我們來看一下BiFunction類,程式碼如下:
package java.util.function;
import java.util.Objects;
/**
* Represents a function that accepts two arguments and produces a result.
* This is the two-arity specialization of {@link Function}.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object, Object)}.
*
* @param <T> the type of the first argument to the function
* @param <U> the type of the second argument to the function
* @param <R> the type of the result of the function
*
* @see Function
* @since 1.8
*/
//這個註解表示是函式式介面
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
//這裡面的default是java8的特性,通過這個關鍵字來設定函式的預設實現,這樣實現類就可以不用實現這個介面,而採用介面中預設的 //實現
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
//下面的一行程式碼返回的是BitFunction<T,U,V>型別物件。
return (T t, U u) -> after.apply(apply(t, u));
首先,執行this.apply(t,u),這裡面的this是呼叫andThen函式的BitFunction類物件。
然後,將返回值傳到after類物件的apply函式中。
最後,返回BiFunction類物件。
這行程式碼等價於:
return new BiFunction<T,U,V>(){
V apply(T t, U u){
return after.apply(value);//這裡面的value為this呼叫apply返回的結果。
}
}
舉一個例子:
public int compute2(int a, b,BitFunction<Integer, Integer,Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(a);
}
呼叫這個方法:
test.compute2(2,3, (v1,v2) -> v1+ v2, value -> value * value);
(value,value) -> value + value是一個BitFunction<Integer, Integer,Integer>類物件,等價於
return new BiFunction<T,U,V>(){
V apply(T t, U u){
return after.apply(V);
}
}值就是function1
同樣value -> value * value等價於
return new Function<R,V>(){
V apply(T t, U u){
return after.apply(V);
}
}值就是function2
所以return function1.andThen(function2).apply(a);執行步驟:
第一步:執行function1.apply(2,3)得到2+3=5。返回一個BiFunction類物件,該類物件中的apply函式執行function2.apply(5)
第二步:執行function2.apply(5)得到5*5=25。
第三步:BiFunction類物件的apply函式中返回25。
詳細的描述請看詳細介紹