Home > OS >  How can I edit the key of Map in java?
How can I edit the key of Map in java?

Time:11-03

for example I want to edit the key that is 2 in this map and make it 3, how can I do that?

Map<Integer,Integer>map=new HashMap<>();
map.put(2,2);
map.get(2)=3;

CodePudding user response:

You can't. You would have to remove the old entry with the old key and add a new one with the new key but the same value

Map<Integer,Integer>map=new HashMap<>();
map.put(2,2);
var removed = map.remove(2);
map.put(3, removed);

CodePudding user response:

Your code says that what you want to do is like map.get(2) = 3, which isn't rewriting the key -- it's updating the value for the key 2.

To do that, you just need map.put(2, 3).

CodePudding user response:

Maps have unique keys. You simply need to write:

map.put(2, 3); 

to change your value for key=2;

  • Related