Is it possible to rename a Hashmap key?

JavaHashmap

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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

Solution 5 - Java

You don't rename a hashmap key, you have to insert a new entry with the new key and delete the old one.

Solution 6 - Java

I'd argue the essence of hasmap keys are for index access purposes and nothing more but here's a hack: making a key-wrapper class around the value of the key so the key-wrapper object becomes the hashmap key for index access, so you may access and change key-wrapper object's value 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

   HashMap<KeyWrapper,String> hashmap=new HashMap<>();
   KeyWrapper key=new KeyWrapper("cool-key");
   hashmap.put(key,"value");
   key.rename("cool-key-renamed");

Though you could also have a non existing key be able to get the value of an existing key from the hashmap but I fear it might be criminal, anyways:

public  class KeyWrapper<T>{

        private T key;
        public KeyWrapper(T key){
            this.key=key;
        }

        @Override
        public boolean equals(Object o) {
            return hashCode()==o.hashCode();
        }

        @Override
        public int hashCode() {
            int hash=((String)key).length();//however you want your hash to be computed such that two different objects may share the same at some point
            return hash;
        }
    }

Example

HashMap<KeyWrapper,String> hashmap=new HashMap<>();
KeyWrapper cool_key=new KeyWrapper("cool-key");
KeyWrapper fake_key=new KeyWrapper("fake-key");
hashmap.put(cool_key,"cool-value");
System.out.println("I don't believe it but its: "+hashmap.containsKey(fake_key)+" OMG!!!");

Solution 7 - Java

In my case had a map containing not real key -> real keys, so I had to replace the not reals with the reals in my map (the idea is like others)

getFriendlyFieldsMapping().forEach((friendlyKey, realKey) ->
    if (map.containsKey(friendlyKey))
        map.put(realKey, map.remove(friendlyKey))
);

Solution 8 - Java

Please look below points:

  1. No,You can not rename the key of HashMap once added.

  2. Very first you have to delete or remove that key and then you can insert with new key with value.

  3. Because in HashMap internal implementation the HashMap key modifier is final.

Solution 9 - Java

You can, if instead of Java native HashMap you'll use a Bimap.
It's not the traditional Map implementation, and you need to make sure it's suits your needs.

> A bimap (or "bidirectional map") is a map that preserves the > uniqueness of its values as well as that of its keys. This constraint > enables bimaps to support an "inverse view", which is another bimap > containing the same entries as this bimap but with reversed keys and > values.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIkesView Question on Stackoverflow
Solution 1 - JavaAlexis PigeonView Answer on Stackoverflow
Solution 2 - JavaMohamed Zakaria El-ZoghbiView Answer on Stackoverflow
Solution 3 - JavaDeepak ManiView Answer on Stackoverflow
Solution 4 - Javalight_rayView Answer on Stackoverflow
Solution 5 - JavaHari MenonView Answer on Stackoverflow
Solution 6 - JavaLiNKeRView Answer on Stackoverflow
Solution 7 - JavaBasheer AL-MOMANIView Answer on Stackoverflow
Solution 8 - JavaGhanshyamView Answer on Stackoverflow
Solution 9 - JavadoronyView Answer on Stackoverflow