Hifzur Rahman
Hifzur Rahman

Reputation: 103

How to modify only the existing key of a hashmap but not its pair?

HashMap<String,String> data = new HashMap<>();

data.put("AAA", "CCC");

I want to replace AAA with BBB during run-time without adding a new key into the map. Is this possible?

Upvotes: 3

Views: 1340

Answers (4)

Kepotx
Kepotx

Reputation: 1082

You can't*

There is no* way to edit existing key, the only way is to remove the old one and add a new key. The most elegant way to do it (IMHO) is this:

map.put( "newKey", map.remove( "oldKey" ) );

*: As @Michael Ziluck say in his comment and answer, you could technically do it with reflection, but as it destroy the integrity of HashTable, you should only do it at your own risk

Upvotes: 4

LenglBoy
LenglBoy

Reputation: 1451

It is not possible to rename/change the old key of a pair - buzzword immutable. You need to remove the object and insert it back with a new key. Here is how it works in detail:

HashMap<String,String> data = new HashMap<>();
data.put("AAA", "CCC");
String value = map.remove("AAA");  // value = "CCC"
map.put("BBB", value);

Of cause you can shortern it to a oneliner like removing the value while setting it. Because remove wwhile return the value. map.put("BBB", map.remove("AAA"))

Upvotes: 2

Michael Ziluck
Michael Ziluck

Reputation: 665

HashMaps are based around hashing the keys, and assuming that the keys never change. For that reason, changing them will break the integrity of the hash table and you will lose all efficiency.

That being said, there IS technically a way to change the key. You would need to look at the source code for the HashMap class and then use reflection to directly edit the key itself.

Upvotes: 2

Mohmmed
Mohmmed

Reputation: 77

Just delete old pair. Make a new pair with the new key and do insert.

Upvotes: 2

Related Questions