给定以下变量
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()); }
我肯定在这里想念的东西:)
您还可以使用Stream.reduce(identity,accumulator,combiner)。
identity是减少函数的初始值accumulator。
identity
accumulator
accumulator减少identity到result,identity如果流是 顺序的 ,这是下一个减少的条件。
result
永远不要在 顺序 流中调用此函数。它计算下一个identity从identity&result在 并行 流。
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);