Can I rename a Hashmap key?

I'm looking for a way to rename a Hashmap key, but I don't know if this is possible in Java.

+78
java hashmap
May 26 '12 at 14:02
source share
7 answers

Try deleting the item and placing it again with a new name. Assuming the keys on your map are String , this can be achieved as follows:

 Object obj = map.remove("oldKey"); map.put("newKey", obj); 
+114
May 26 '12 at 2:05 p.m.
source share
— -

Assign the value of the key to be renamed to the new key. And delete the old key.

 hashMap.put("New_Key", hashMap.get("Old_Key")); hashMap.remove("Old_Key"); 
+17
Dec 18 '13 at 6:07
source share
 hashMap.put("New_Key", hashMap.remove("Old_Key")); 

This will do what you want, but you will notice that the key location has changed.

+11
Oct 30 '16 at 14:27
source share

You cannot rename / change the hashmap key after adding.

The only way is to delete / delete the key and insert a new key and value pair.

Reason : in the hashmap internal implementation, the Hashmap key modifier is 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

+7
Jun 26 '15 at 9:19
source share

You do not rename the hashmap key, you need to insert a new record with a new key and delete the old one.

+4
May 26 '12 at 14:05
source share

You can if instead of Java HashMap you will use Bimap .
This is not a traditional Map implementation, and you need to make sure that it meets your needs.

A bidirectional card (or “bidirectional card”) is a card that preserves the uniqueness of its values, as well as keys. This limitation allows bimaps to maintain an "inverse representation", which is another bimap containing the same entries as this bimap, but with reversed keys and values.

Using bimap, you can invert the view and replace the key.
Checkout Apache Commons BidiMap and Guava BiMap .

0
Jun 06 '19 at 1:55
source share

I would say that the essence of hasmap keys for index access purposes is nothing more than hacking: creating a wrapper class for keys around the key value so that the key wrapper object becomes a hash key for accessing the index, so You can access and change the value of the key shell object for your specific needs:

 public class KeyWrapper<T>{ private T key; public KeyWrapper(T key){ this.key=key; } public void rename(T newkey){ this.key=newkey; } } 
Example

Example

  HashMap<KeyWrapper,String> hashmap=new HashMap<>(); KeyWrapper key=new KeyWrapper("cool-key"); hashmap.put(key,"value"); key.rename("cool-key-renamed"); 
0
Jul 28 '19 at 18:15
source share



All Articles