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?
Asked
Active
Viewed 6.2k times
9
-
4Just `put` a new value for the same key. – Oliver Charlesworth Aug 12 '14 at 22:16
1 Answers
25
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}

Luiggi Mendoza
- 85,076
- 16
- 154
- 332
-
It's still not giving me the correct output. Maybe its the contain method I am using. – pgray10 Aug 13 '14 at 23:17
-
Here is my code: if (item.contains("music")) { double newprice = Double.parseDouble(price); newprice = newprice *1.10; String newprice2 = String.valueOf(newprice); cart.put(item, newprice2); } – pgray10 Aug 13 '14 at 23:25
-
You're using contains for "music" key but the replace uses `item` variable as key, which may not be the same value. Provide a code to replicate your specific problem. – Luiggi Mendoza Aug 14 '14 at 01:35
-
@pgray10 please provide the `equals` and `hashCode` implementation for your the class of your `item` variable as well. – Luiggi Mendoza Aug 14 '14 at 15:02
-