1
        HashMap<String, String> apos = new HashMap<String, String>();
        apos.put("i'm","I am");
        apos.put("can't","cannot");
        apos.put("couldn't","could not");
        String[] st = new String[]{"i'm","johny"};
        Iterator itr = apos.entrySet().iterator();
        for (int i = 0; i < st.length; i++) {
            while((itr).hasNext()) {
                if (itr.equals(st[i]))
                {
                    st[i].replace(st[i],??????(value of the matched key))
                }   
            }

            }

I want to compare a string with hashmap and rerplace a word with hashmap value if it matches with its key. Above is what i am trying to do. Could anyone will please help me what i should write in place of key.

Help will be appreciated. Thanks

2 Answers 2

2
  1. You don't need to iterate over the map to find out whether an array value is a key in map. Use Map#containsKey() method for that. So, get rid of that iterator.

    if (map.containsKey(s[i]))
    
  2. You don't need a replace at all. You can simply assign a new value to an array index using = operator.

    s[i] = newValue;
    
  3. To get the value from the map for a particular key to set in the array, use Map#get(Object) method.

    map.get(s[i]);
    
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Rohit for replying... I tried this : for (int i = 0; i < st.length; i++) { while(apos.containsKey(s[i])) { s[i]=s[i].replace(s[i],apos.get(s[i])); } System.out.println(s[i]); } and i am getting desired result but i did't got your 2nd point, could you please elaborate it. Thanks a ton.
@user2805482. That is not really related to your question, as I see now. I'll remove it. But just for explanation, since String are immutable, replacing anything in a String will give you a new String. It doesn't do a in-place replacement.
In your current code: change s[i]=s[i].replace(s[i],apos.get(s[i])); to s[i] = apos.get(s[i]);. That was my 3rd point. And change your while(apos.containsKey()) to if (apos.containsKey()), else it will be an infinite loop.
0

Try this out: Instead of st[i].replace(st[i],??????(value of the matched key))

use

   if(st[i].equals((String)itr.getKey()))
     st[i] = (String)itr.getValue(); 

Refer to this tutorial for usage details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.