[英]Java 8 streams.reduce() with combiner
我的問題是我想細分以下代碼
我有一張地圖,我想用以下reduce()函數用地圖的值替換某些字符串:
Map<String, String> environmentMap = new HashMap<>();
Function<String, String> replaceFunction = environmentMap.entrySet()
.stream()
.reduce
(Function.identity(),
(function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue(),
Function::andThen);
不知何故我對replaceFunction部分感到困惑,但讓我根據自己的理解將其分解。
environmentMap.entrySet().stream()
將創建Entry<String,String>
的流。 reduce()
方法采用一個標識,一個累加器和一個組合器。 BinaryOperator<T>
嗎? Function.identity()
將始終返回一個返回輸入參數的Function。 在這種情況下,類型為String
(function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()
。 BiFunction<T, U, R>
的返回類型Function<String,String>
來自BiFunction<T, U, R>
? Function<String, String> replaceFunction = environmentMap.entrySet()
.stream()
.reduce(Function.identity(),
(function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue())),
Function::andThen);
environmentMap.entrySet().stream()
將創建Entry<String,String>
的流。 我正在使用的reduce()
方法采用一個標識,一個累加器和一個Combiner.item 。
到此為止您是正確的,但是標識,累加器和組合器的解析如下:
Function.identity()
被解析為Function<String, String>
。 累加器 - (function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()))
。
這是下面的部分
`stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()))`
解析為Function<String, String>
。
這樣整個累加器就解決了
`BiFunction<Function<String,String>, Entry<String,String>,Function<String,String>`
組合器 Function::andThen
解析為BinaryOperator<Function<String,String>, Function<String,String>>
因此,在6和7中回答您的問題, Function::andThen
充當組合器; 7是如上所述的累加器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.