小编典典

用Java8 Lambda函数替换全部

java

给定以下变量

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

我想使用以下代码将占位符$ {name}替换为值“ Joe”(不起作用)

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

但是,如果我采用“旧式”方式,则一切都将正常运行:

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

我肯定在这里想念的东西:)


阅读 716

收藏
2020-11-16

共1个答案

小编典典

您还可以使用Stream.reduce(identity,accumulator,combiner)

身份

identity是减少函数的初始值accumulator

累加器

accumulator减少identityresultidentity如果流是 顺序的 ,这是下一个减少的条件。

合路器

永远不要在 顺序 流中调用此函数。它计算下一个identityidentityresult并行 流。

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);
2020-11-16