Replace String values โ€‹โ€‹with a hash map value

I am new to Java programming. I created a hash map that contains my key value pairs in order to use the value corresponding to the corresponding key when replacing user input.

i.e.

HashMap<String,String> questionKey = new HashMap<>(); for (item : itemSet()) { questionKey.put(String.valueOf(item.getOrder()+1), item.getKey()); } String list = commandObject.getObjectItem().getList(); if (list.contains("q")){ list.replaceAll("q01", questionKey.get("1")); commandObject.getObjectItem().setList(list); } 

I use this in evaluating a formula

Note. Users are given a specific way to enter a specific formula (value1 + value2 + value3)

I take this value (value1 value2 value3) and convert it to (value1key value2key value3key)

Update:

The question, as I understand it, is now better to help better understand how to use a hash map to evaluate user input. More clear question:

What would be the best approach to evaluate ie

User input = "var1 + var2"

Expected value: valueOf (var1) + valueOf (var2)

?

+5
source share
3 answers
 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); } } 
+3
source
 @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. A good day

For something more complicated, I would rather use OGNL .

+19
source

Java 8 reveals the functional approach that is given in this post .
You simply create a new function for each word on the map and chain them together. eg:

 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); } 
+2
source

Source: https://habr.com/ru/post/1500383/


All Articles