Use StringSubstitutor from Apache Commons Text.
Dependency import
Import the Apache commons text dependency using maven as bellow:
Copy<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
Example
CopyMap<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
Answer from JH. on Stack OverflowI know in JavaScript there are template strings that allow you to do this:
const firstStr = 'hello';
const secondStr = 'world';
const templateStr = `${firstStr} ${secondStr}`;I can't seem to find anything that lets you do this in Java. Is there the same capability in Java? Concatenation just looks ugly to me. I saw this:
https://teamtreehouse.com/community/are-there-no-template-literals-in-java
but it requires your output to be put through
System.out.printf();
instead of
System.out.printl();
I'm specifically looking for a way to store a template literal in a variable like line 3 in the example above.
Thanks!
Videos
Use StringSubstitutor from Apache Commons Text.
Dependency import
Import the Apache commons text dependency using maven as bellow:
Copy<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
Example
CopyMap<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
Take a look at the java.text.MessageFormat class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.
CopyObject[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);