Updating a java map entry

I'm facing a problem that seems to have no straighforward solution.

I'm using java.util.Map, and I want to update the value in a Key-Value pair.

Right now, I'm doing it lik this:

private Map<String,int> table = new HashMap<String,int>();
public void update(String key, int val) {
if( !table.containsKey(key) ) return;
Entry<String,int> entry;
for( entry : table.entrySet() ) {
if( entry.getKey().equals(key) ) {
entry.setValue(val);
break;
}
}
}

So is there any method so that I can get the required Entry object without having to iterate through the entire Map? Or is there some way to update the entry's value in place? Some method in Map like setValue(String key, int val)?

jrh

140619 次浏览

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key,V value):将指定值与此映射中的指定键关联(可选操作)。如果映射以前包含键的映射,则旧值将替换为指定的值。(当且仅当M.ContainsKey(K)将返回真时,才称映射M包含密钥K的映射。)

You just use the method

public Object put(Object key, Object value)

if the key was already present in the Map then the previous value is returned.

If key is present table.put(key, val) will just overwrite the value else it'll create a new entry. Poof! and you are done. :)

you can get the value from a map by using key is table.get(key); That's about it