将字符串值替换为哈希映射中的值

时间:2013-09-03 20:35:02

标签: java replace hashmap

我是Java编程的新手。我创建了一个哈希映射,其中包含我的键值对,用于将用户输入替换为与相应键对应的值。

即。

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

我在公式评估中使用它

注意:为用户提供特定的公式特定的输入方式(value1 + value2 + value3)

我正在接受(value1 value2 value3)并将其转换为(value1key value2key value3key)

更新:

我现在更好地理解的问题是为了帮助更好地理解如何利用散列图来评估用户输入。更明确的问题是

评估表达式的最佳方法是什么,

用户输入=“var1 + var2”

预期值:valueOf(var1)+ valueOf(var2)

3 个答案:

答案 0 :(得分:19)

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

输出:

Hello DD84,欢迎使用Stack Overflow。祝你有愉快的一天

对于更复杂的事情,我宁愿使用OGNL

答案 1 :(得分:2)

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

    }
}

答案 2 :(得分:1)

Java 8揭示了此post中给出的一种功能方法。
您只是为地图中的每个单词创建一个新功能并将它们链接在一起。 例如:

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);
}
相关问题