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
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.
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.
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.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With