ReplaceAll with java8 lambda functions

前端 未结 6 1652
清歌不尽
清歌不尽 2021-01-02 04:57

Given the following variables

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

I would like to replace the placeholder ${na

6条回答
  •  一生所求
    2021-01-02 05:46

    import java.util.HashMap;
    import java.util.Map;
    
    public class Repl {
    
        public static void main(String[] args) {
            Map variables = new HashMap<>();
            String templateText = "Hi, ${name} ${secondname}! My name is ${name} too :)";
            variables.put("name", "Joe");
            variables.put("secondname", "White");
    
            templateText = variables.keySet().stream().reduce(templateText, (acc, e) -> acc.replaceAll("\\$\\{" + e + "\\}", variables.get(e)));
            System.out.println(templateText);
        }
    
    }
    

    output:

    Hi, Joe White! My name is Joe too :)

    However, it's not the best idea to reinvent the wheel and the preferred way to achieve what you want would be to use apache commons lang as stated here.

     Map valuesMap = new HashMap();
     valuesMap.put("animal", "quick brown fox");
     valuesMap.put("target", "lazy dog");
     String templateString = "The ${animal} jumped over the ${target}.";
     StrSubstitutor sub = new StrSubstitutor(valuesMap);
     String resolvedString = sub.replace(templateString);
    

提交回复
热议问题