Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to rename a Hashmap key?

Tags:

java

hashmap

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

like image 351
Ikes Avatar asked May 26 '12 14:05

Ikes


People also ask

How do you replace a key on a map?

HashMap replace() Method in Java The replace(K key, V value) method of HashMap replaces an entry for the specified key. It returns replaced value. It returns null if the map does not contain an entry for the specified key.

How do I change the value of a key in a HashMap in Java?

hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.

Can we update HashMap while iterating?

Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the ...

Can a HashMap key be duplicated?

HashMap stores key, value pairs and it does not allow duplicate keys.


1 Answers

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); 
like image 152
Alexis Pigeon Avatar answered Sep 18 '22 15:09

Alexis Pigeon