How to best parameterize a string

1.8k Views Asked by At

For example I have:

String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}."
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");

Desired output: "Hi Bob, you have successfully ordered a sofa."

What would be the best (foolproof, maintainable, time efficient, etc.) way to get the desired output?

I thought of doing something simple:

String output = templateString;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
    output = output.replace("{{" + entry.getKey() + "}}", entry.getValue());
}

Is there a better way?

4

There are 4 best solutions below

0
On

Depends how sophisticated a templating system you need. There are many out there already.

Two examples are:

0
On

Another way is to use 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());
1
On

Would be better to fetch values using keys in Map

            String output = templateString;
            output = output.replace("{{customerName}}",parameters.get("customerName"));
            output = output.replace("{{itemName}}",parameters.get("itemName"));
0
On

Apart from the solutions already provided in other answers, you can also use StringSubstitutor from Apache Commons Text.

An example from https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html :-

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