问题
I'm looking for a way to rename a Hashmap key, but i don't know if it's possible in Java.
回答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);
回答2:
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");
回答3:
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.
回答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
回答5:
You don't rename a hashmap key, you have to insert a new entry with the new key and delete the old one.
回答6:
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");
回答7:
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.
来源:https://stackoverflow.com/questions/10766906/is-it-possible-to-rename-a-hashmap-key