我有一個Function
andBiFunction
我想把它們鎖起來
Function<Integer, String> function = n -> "" n;
BiFunction<String, Boolean, List<Character>> biFunction = (str, isOK) -> Collections.EMPTY_LIST;
有沒有辦法鏈接這兩個函式,例如回傳值 fromfunction
用作輸入biFunction
public List<Character> myMethod(int n, boolean isOK) {
return function.andThen(biFunction).apply([output_of_function], isOK)
}
我找不到將整數提供n
給function
也不提供biFunction
第一個輸出的方法function
。
可行嗎?
uj5u.com熱心網友回復:
andThen()
介面中compose()
宣告的默認方法Function
期望另一個Function
作為引數。無法融合Function
和BiFunction
。
另一方面,方法BiFunction.andThen()
需要一個Function
as 引數。但不幸的是,它將在 之后應用BiFunction
,但您需要相反,因此此選項不適合您的用例。
您可以將它們組合成一個期望函式的輸入Function
和一個值并生成由 by 生成的結果,如下所示:BiFunction
BiFunction
Function
boolean
BiFunction
public static <T, R, RR> BiFunction<T, Boolean, RR> getCombinedFunction(
Function<T, R> fun, BiFunction<R, Boolean, RR> biFun
) {
return (t, isOk) -> biFun.apply(fun.apply(t), isOk);
}
并以下列方式使用它:
Function<Integer, String> function = // initializing function
BiFunction<String, Boolean, List<Character>> biFunction = // initializing biFunction
List<Character> chars = getCombinedFunction(function, biFunction).apply(12345, true);
uj5u.com熱心網友回復:
您可以像這樣定義組成 Function 和 BiFunction 的通用方法。
public static <A, B, C, D> BiFunction<A, C, D> compose(Function<A, B> f, BiFunction<B, C, D> bf) {
return (a, c) -> bf.apply(f.apply(a), c);
}
你可以像這樣使用。
Function<Integer, String> function = n -> "" n;
BiFunction<String, Boolean, List<Character>> biFunction = (str, isOK) -> Collections.emptyList();
public List<Character> myMethod(int n, boolean isOK) {
return compose(function, biFunction).apply(n, isOK);
}
節點:您應該使用Collections.emptyList()
而不是Collections.EMPTY_LIST
. 后者給出警告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521549.html
標籤:爪哇
上一篇:不可修改的多圖