例如,我有:
String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}."
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");
所需的输出:
"Hi Bob, you have successfully ordered a sofa."
获得所需输出的最佳方法(安全,可维护,省时等)是什么?
我想到了做一些简单的事情:
String output = templateString;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
output = output.replace("{{" + entry.getKey() + "}}", entry.getValue());
}
有更好的方法吗?
答案 0 :(得分:1)
答案 1 :(得分:0)
另一种方法是使用Mustache.java
,docs
String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}.";
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");
Writer writer = new StringWriter();
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(new StringReader(templateString), "example");
mustache.execute(writer, parameters);
writer.flush();
System.out.println(writer.toString());
答案 2 :(得分:0)
使用Map中的键来获取值会更好
String output = templateString;
output = output.replace("{{customerName}}",parameters.get("customerName"));
output = output.replace("{{itemName}}",parameters.get("itemName"));
答案 3 :(得分:0)
除了其他答案中已经提供的解决方案之外,您还可以使用 Apache Commons Text 中的StringSubstitutor
。
Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumps over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);