develop with

How to use a simple string template in java

Using Apache Commons Lang for simple string templates

The simpliest way to have a string template in java is by using the Apache Commons Lang library which you already have as a dependency already.

Get library

Resolve the dependency through maven by defining it in your pom.xml.


String template usage

To use the string template approach from Apache Commons Lang library, you first define your data with a Map. Then, you develop your template via a simple string or load it from a file. The template format is very similar to Kotlin String Templates, Velocity or Freemarker. The values are defined with the syntax ${map_key}.


 Map<String, String> valuesMap = new HashMap<String, String>();
 valuesMap.put("name", "John Doe");
 String templateString = "Welcome ${name}.";
 StrSubstitutor sub = new StringSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

This is a great way for setting up a string template for testing or one off templates within your application.

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.