Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the value of a key in a hash map? [duplicate]

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?

like image 692
pgray10 Avatar asked Aug 12 '14 22:08

pgray10


People also ask

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

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.

Can we duplicate values in HashMap?

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.

Can we replace key in map?

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.

Can we store a duplicate key in hash table?

it can have duplicate values but not keys.


1 Answers

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}
like image 168
Luiggi Mendoza Avatar answered Oct 13 '22 18:10

Luiggi Mendoza