How to modify the value of a map in Java?
To change the value of a Map, you can use the put() method to replace the value corresponding to the specified key.
The example code is as follows:
// 创建一个Map对象
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 修改指定key的value值
map.put("B", 4);
// 输出修改后的Map
System.out.println(map);
Running the above code will output: {A=1, B=4, C=3}, indicating that the value corresponding to “B” has been changed to 4.
If the key to be modified does not exist in the Map, the put() method will add the new key-value pair to the Map.
Note: The key of a Map is unique, if the key being modified already exists in the Map, the new value will replace the old value.