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
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]);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.