The following method works. I am looking for advice to make it more readable. To see if I could avoid any unneccesary checks / casting and the instance of check. Also not a fan of having to recreate the initial String with every loop but not sure if there is a way around it.
Things to note.
I am using Java 8 and Spring boot.
I can't change the productMap. It will remain as a Map < String, Object> .
Can use external library Apache commons but not Guava.
It is possible for initialText and productMap to be null / empty.
In the map, I am only looking for values which are of type String and value contains only numbers. If it exists, I want to use it and replace initialText
Example scenario with following data in the parameters being passed in:
String initialText = "This is a sample text with PLACEHOLDER and yet another PLACEHOLDER and more message."
productMap = {
"Some key" : new SomeObject(), // I won't use this cos value is not String.
"PLACEHOLDER" : "26000", // I will use this to replace cos the key PLACEHOLDER exists in above text and it contains only numbers.
"SOME_OTHER" : "SOME_TEXT", // it is a String value but the key doesn't exist in the initial text thus no difference.
}
After executing the following code, I expect the method to return the updated String as follows (notice the comma due to String format):
"This is a sample text with 26,000 and yet another 26,000 and more message."
Method as follows. Appreciate the advices. Thanks.
public String update(String initialText, Map<String, Object> productMap){
if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){
return initialText;
}
for (Map.Entry<String, Object> productData : productMap.entrySet()) {
String key = productData.getKey();
Object value = productData.getValue();
if(value instanceof String && ((String) value).matches("[0-9]+")){
String offerValue = (String)value;
initialText = initialText.replaceAll(key, String.format("%,d", Integer.parseInt(offerValue)));
}
}
return initialText;
}
public String format()
. Then you can do allwaysvalue.format()
These objects can get more infos like decimal places. \$\endgroup\$