Reputation: 1647
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
Reputation: 213411
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]))
You don't need a replace at all. You can simply assign a new value to an array index using =
operator.
s[i] = newValue;
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