Explorer
Explorer

Reputation: 1647

replace array value with hashmap values

        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

Upvotes: 1

Views: 1290

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213411

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

Upvotes: 2

Trey Jonn
Trey Jonn

Reputation: 360

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.

Upvotes: 0

Related Questions