Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace String values with value in Hash Map

I'm new to Java Programming. I have created a hash map that contains my Key Value pairs to utilize in replacing user input with the value corresponding to the respective key.

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 am using this in a formula evaluation

Note: Users are given a certain formula specific way of entry (value1 + value2 + value3)

I'm taking that (value1 value2 value3) and converting it to (value1key value2key value3key)

Update:

The Question as I understand it better now was meant to be to help better understand how to utilize a hashmap in order to evaluate user input. The more clear question would be

What would be the best approach to evaluate an expression i.e.

User Input = "var1 + var2"

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

?

like image 272
DD84 Avatar asked Sep 03 '13 20:09

DD84


2 Answers

@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.

like image 93
Alfredo Osorio Avatar answered Oct 07 '22 12:10

Alfredo Osorio


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);

    }
}
like image 26
DD84 Avatar answered Oct 07 '22 14:10

DD84