Reputation: 371
My question is that i would like a breakdown of the following code
I have a map and i want to replace certain strings with the map's value with the following reduce() function:
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);
Somehow i'm confused on the replaceFunction part but let me break it down based on my understanding.
environmentMap.entrySet().stream()
will create a stream of Entry<String,String>
.reduce()
method that i am using takes an identity, accumulator, and a combiner.BinaryOperator<T>
?Function.identity()
will always return a Function that returns the input argument. In this case of type String
(function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()
.Function<String,String>
in the BiFunction<T, U, R>
came from??Upvotes: 1
Views: 2151
Reputation: 1199
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()
will create a stream of Entry<String,String>
.The reduce()
method that i am using takes an identity, accumulator, and a combiner.item.
Till this you are right, but the identity, accumulator, and combiner gets resolved as follows:
Function.identity()
gets resolved to Function<String, String>
.accumulator - (function,entrySet) -> stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()))
.
Here the following part,
`stringToReplace -> function.apply(stringToReplace.replaceAll(entrySet.getKey(),entrySet.getValue()))`
gets resolved into Function<String, String>
.
And so this entire accumulator gets resolved to
`BiFunction<Function<String,String>, Entry<String,String>,Function<String,String>`
combiner - Function::andThen
gets resolved to BinaryOperator<Function<String,String>, Function<String,String>>
So, to answer your question in 6 and 7, Function::andThen
acts as the combiner; and 7 is the accumulator as I described above.
Upvotes: 1