Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 603
Hifzur Rahman Avatar asked Dec 17 '25 23:12

Hifzur Rahman


2 Answers

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

like image 89
Kepotx Avatar answered Dec 20 '25 18:12

Kepotx


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

like image 41
Mohmmed Avatar answered Dec 20 '25 17:12

Mohmmed