Replace String values with value in Hash Map
@Test
public void testSomething() {
String str = "Hello ${myKey1}, welcome to Stack Overflow. Have a nice ${myKey2}";
Map<String, String> map = new HashMap<String, String>();
map.put("myKey1", "DD84");
map.put("myKey2", "day");
for (Map.Entry<String, String> entry : map.entrySet()) {
str = str.replace("${" + entry.getKey() + "}", entry.getValue());
}
System.out.println(str);
}
Output:
Hello DD84, welcome to Stack Overflow. Have a nice day
For something more complex I'd rather use OGNL.
import java.util.HashMap;
class Program
{
public static void main(String[] args)
{
String pattern = "Q01 + Q02";
String result = "";
HashMap<String, String> vals = new HashMap<>();
vals.put("Q01", "123");
vals.put("Q02", "123");
for(HashMap.Entry<String, String> val : vals.entrySet())
{
result = pattern.replace(val.getKey(), val.getValue());
pattern = result;
}
System.out.println(result);
}
}
Java 8 reveals a functional approach which is given in this post.
You are just creating a new function for each word in your map and chain them together.
e.g:
public static void main(String[] args) {
Map<String, String> dictionary = new HashMap<>();
String stringToTranslate = "key1 key2"
dictionary.put("key1", "value1");
dictionary.put("key2", "value2");
String translation = dictionary.entrySet().stream()
.map(entryToReplace -> (Function<String, String>) s -> s.replace(entryToReplace.getKey(),
s.replace(entryToReplace.getValue())
.reduce(Function.identity(), Function::andThen)
.apply(stringToTranslate);
}