views:

1433

answers:

3

Hi,

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

+7  A: 

What's wrong with just

table.put(key, val);

?

skaffman
the key already exists. will it case a problem?
Here Be Wolves
No, the old value for that key will be overwritten.
skaffman
oh, cool. I wish this was said somewhere in the docs. Maybe I didn't read properly.
Here Be Wolves
The javadocs for the likes of HashMap is very expansive. What docs are you reading?
skaffman
From the javadoc: 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.)
skaffman
like I said: didn't read the docs well :) yes, I was reading javadocs for the Map interface
Here Be Wolves
+1  A: 

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.

mkoeller
+1  A: 

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); Thats about it

Priyank