9

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)

?

DD84
  • 383
  • 1
  • 6
  • 15
  • 1
    Which is the question/issue? – SJuan76 Sep 03 '13 at 20:37
  • 2
    Your code won't even remotely compile. Not even sure what you're trying to achieve is understandable. Please provide compilable code, stack trace if any, and a clearer scope. – Mena Sep 03 '13 at 20:37
  • 2
    and the question is..? – Prabhaker A Sep 03 '13 at 20:37
  • @SJuan76 To Clarify this is a Spring Application and I am attempting to take the user's input and replace with the corresponding keyValue when the form is submitted to the database as a reference for later formula calculation. – DD84 Sep 03 '13 at 20:43
  • @Mena I can post the pseudo code with a few more details if that would help. – DD84 Sep 03 '13 at 20:44
  • @DD84 I'm sorry to say, but in my personal opinion the nature of your question does not qualify you for a better answer than Alfredo's. By the way, Alfredo's answer might not be not top-notch, but I believe it's only mildly ironic, not sarcastic, and not aimed at ridiculing you in any way. I personally won't +1, yet I strongly advise you to take a closer look and learn from it, as that's your declared intent. Alfredo's question will compile, and it can teach you a thing or two. – Mena Sep 03 '13 at 21:13

3 Answers3

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

Alfredo Osorio
  • 11,297
  • 12
  • 56
  • 84
  • 4
    I dread asking questions in forums or on this site because all I receive is ridicule even as a beginner. I'm trying to learn just as anyone else. @AlfredoOsorio thanks for you answer but do to it's sarcastic nature I choose not to accept it as my answer. – DD84 Sep 03 '13 at 20:55
  • 6
    @DD84 Just a friendly advice, the important thing here is to learn. I do not think Sarcasm should take effect here in any way. Just take it for now and then maybe after some months answer some of Alfredo's questions. :) – JNL Sep 03 '13 at 21:34
4

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);
}
David Barda
  • 958
  • 10
  • 28
  • It's more efficient to iterate over the string than over the map. The string might be short, and the map may contain millions of entries. – Roland Illig Apr 19 '19 at 14:08
  • 2
    Oh compiled error. I think you should fix line `.map(entryToReplace -> (Function) s -> s.replace(entryToReplace.getKey(), s.replace(entryToReplace.getValue())` to `.map(entryToReplace -> (Function) s -> s.replace(entryToReplace.getKey(), entryToReplace.getValue()))` – yuen26 Dec 30 '19 at 01:12
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);

    }
}
cjsimon
  • 1,121
  • 12
  • 22
DD84
  • 383
  • 1
  • 6
  • 15