Is it possible to rename a Hashmap key?
I'm looking for a way to rename a Hashmap key, but i don't know if it's possible in Java.
Solution 1:
Try to remove the element and put it again with the new name. Assuming the keys in your map are String
, it could be achieved that way:
Object obj = map.remove("oldKey");
map.put("newKey", obj);
Solution 2:
hashMap.put("New_Key", hashMap.remove("Old_Key"));
This will do what you want but, you will notice that the location of the key has changed.
Solution 3:
Assign the value of the key, which need to be renamed, to an new key. And remove the old key.
hashMap.put("New_Key", hashMap.get("Old_Key"));
hashMap.remove("Old_Key");
Solution 4:
You cannot rename/modify the hashmap key
once added.
Only way is to delete/remove the key
and insert with new key
and value
pair.
Reason : In hashmap internal implementation the Hashmap key
modifier marked as final
.
static class Entry<K ,V> implements Map.Entry<K ,V>
{
final K key;
V value;
Entry<K ,V> next;
final int hash;
...//More code goes here
}
For Reference : HashMap