I have created a hash map that the users input the key and the value. I want to be able to change the value of the hash map if a specific key is entered. I tried the setValue
method but got nothing. The value and the key are both strings. What method would I use to change this?
The merge Method. The merge method updates the value of a key in the HashMap using the BiFunction if there is such a key. Otherwise, it will add a new (key, value) pair, with the value set to the value provided as the second argument to the method.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
it can have duplicate values but not keys.
Just use Map#put
using the current old key and the new value:
Map<String, String> map = new HashMap<>();
map.put("user", "Luiggi Mendoza");
System.out.println(map);
//replacing the old value
map.put("user", "Oli Charlesworth");
System.out.println(map);
Output:
{user=Luiggi Mendoza}
{user=Oli Charlesworth}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With