Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a java map entry

Tags:

java

in-place

map

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

like image 299
jrharshath Avatar asked Jun 30 '09 07:06

jrharshath


People also ask

How do you update a map entry?

The simplest way to update a map entry is with the map. put method. If the key already exists in the map, Hazelcast will replace the stored value with the new value. If the key does not exist in the map, Hazelcast will add it to the map.

Can I update map while iterating Java?

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.

Can we update key in map in Java?

Increase the value of a key in HashMap 2.1 We can update or increase the value of a key with the below get() + 1 method. 2.2 However, the above method will throw a NullPointerException if the key doesn't exist. The fixed is uses the containsKey() to ensure the key exists before update the key's value.


2 Answers

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

like image 88
skaffman Avatar answered Sep 22 '22 03:09

skaffman


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

like image 31
Priyank Avatar answered Sep 24 '22 03:09

Priyank