ReplaceAll with java8 lambda functions

user3727540 :

Given the following variables

templateText = "Hi ${name}";
variables.put("name", "Joe");

I would like to replace the placeholder ${name} with the value "Joe" using the following code (that does not work)

 variables.keySet().forEach(k -> templateText.replaceAll("\\${\\{"+ k +"\\}"  variables.get(k)));

However, if I do the "old-style" way, everything works perfectly:

for (Entry<String, String> entry : variables.entrySet()){
    String  regex = "\\$\\{" + entry.getKey() + "\\}";          
    templateText =  templateText.replaceAll(regex, entry.getValue());           
   }

Surely I am missing something here :)

holi-java :

you also can using Stream.reduce(identity,accumulator,combiner).

identity

identity is the initial value for reducing function which is accumulator.

accumulator

accumulator reducing identity to result, which is the identity for the next reducing if the stream is sequentially.

combiner

this function never be called in sequentially stream. it calculate the next identity from identity & result in parallel stream.

BinaryOperator<String> combinerNeverBeCalledInSequentiallyStream=(identity,t) -> {
   throw new IllegalStateException("Can't be used in parallel stream");
};

String result = variables.entrySet().stream()
            .reduce(templateText
                   , (it, var) -> it.replaceAll(format("\\$\\{%s\\}", var.getKey())
                                               , var.getValue())
                   , combinerNeverBeCalledInSequentiallyStream);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437119&siteId=1
Recommended