78

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

newacct
  • 119,665
  • 29
  • 163
  • 224
jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • PS: its table.entrySet(). I typed it wrong here. – jrharshath Jun 30 '09 at 07:11
  • You can remove the first "if" statement. It still causes a full iteration through the map if the key is not present. If you remove it, you will still iterate through the whole map and not execute anything if the key isn't present. Right now if the key is present, you iterate through the map, find that it is present, and then iterate through the entries again. – Sandy Simonton Jul 23 '15 at 23:48

3 Answers3

165

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.)

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
skaffman
  • 398,947
  • 96
  • 818
  • 769
13

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

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Priyank
  • 14,231
  • 18
  • 78
  • 107
6

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
  • 4,469
  • 23
  • 30