17

in javascript I can write the follow code:

response = {
    status: 1,
    data: {
        key : 2
    }
}
var result = `status is ${response.status}, data key is ${response.data.key}`
console.log(result);

the output is

status is 1, data key is 2

Is there any libs provide the way to do it in java, providing the following function?

String xxxFunction(Map map, String template)

please note the usage of ${response.data.key}, map in map

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
fudy
  • 1,540
  • 5
  • 25
  • 41

2 Answers2

23

You can make use of String.format

String template = "status is %s, data key is %s"
String result = String.format(template, status, key);
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    While this may answer the question, you should expand your answer by providing some explaining text and documentation for further reading. – hellow Aug 16 '18 at 11:10
  • 3
    Not the same thing... – theMayer Jan 09 '20 at 16:45
  • @theMayer - what do you mean ? – MasterJoe Aug 04 '20 at 21:38
  • 3
    @MasterJoe, string.format is not the same thing - not even close to the same thing - as a template literal. In fact, it’s what you’re trying to avoid with a template literal. So the correct answer is “Java doesn’t offer this.” Game, set, and match to C# – theMayer Aug 06 '20 at 11:58
3

You can try StrSubstitutor from Apache common text

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

You can find a download link / dependency here

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51