Java 用哈希映射中的值替换字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18601011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:23:47  来源:igfitidea点击:

Replace String values with value in Hash Map

javareplacehashmap

提问by DD84

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.

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

i.e.

IE

        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)

:给用户一定的公式特定的输入方式(value1+value2+value3)

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

我把那个 (value1 value2 value3) 转换成 (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"

用户输入 = "var1 + var2"

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

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

?

?

采纳答案by DD84

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

    }
}

回答by Alfredo Osorio

@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

你好 DD84,欢迎来到 Stack Overflow。祝你今天过得愉快

For something more complex I'd rather use OGNL.

对于更复杂的东西,我宁愿使用OGNL

回答by David Barda

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:

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

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