Updating a java map entry

jrharshath picture jrharshath · Jun 30, 2009 · Viewed 129.3k times · Source

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

Answer

skaffman picture skaffman · Jun 30, 2009

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): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)