0

I have a string

String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

But there is no entry for attr target in valuesMap. Final resolvedString would be The quick brown fox jumps over the ${target}.

Instead of ${target}, it need to be empty. Values in templatestring which doesn't have key in map should be empty or null.

required The quick brown fox jumps over the.

How to handle this

1 Answers1

0

Your Map<String,String> valuesMap contains just the couple key, value "animal", "quick brown fox", you have to add the couple "target", "" to your map like below:

String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", ""); //<-- adding the new couple to the map
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
dariosicily
  • 1,062
  • 1
  • 4
  • 9
  • Just now checked in documentation of strsubstitutor. We can use delimiter to set default value in template string Replying to your Answer, If i get that map from an external api, which doesn't include key if its null. How do you proceed this case? (keys are dynamic) – Karthik Ckn Sep 09 '20 at 13:58
  • @KarthikCkn If I understand well you do not want to modify the original map from the external api and set an empty default value, in this case you can use `:-` operator in your string template with an empty default value like The `${animal} jumps over the ${target:-}`. – dariosicily Sep 09 '20 at 15:48