ReplaceAll与java8 lambda函数 [英] ReplaceAll with java8 lambda functions

查看:835
本文介绍了ReplaceAll与java8 lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下变量

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

我想使用以下代码将占位符$ {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 :)

推荐答案

你也可以使用 Stream.reduce(identity,accumulator,combiner)

身份是减少功能的初始值是累加器

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

累加器身份减少到结果,这是身份,如果流顺序,则下一次减少。

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

此函数永远不会在顺序流中调用。它从身份计算下一个身份& 并行流中的结果

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);

这篇关于ReplaceAll与java8 lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆