To change the value of an entry in a HashMap
in Java, you can use the put
method of the HashMap
class. This method takes two arguments: the key of the entry and the new value for that entry.
For example, given a HashMap
called map
that maps strings to integers, you could change the value of the entry with key "foo" as follows:
map.put("foo", newValue);Source:www.lautturi.com
This will update the value for the key "foo" in the HashMap
to be newValue
. If there is no entry with key "foo" in the HashMap
, this method will add a new entry with key "foo" and value newValue
.
Here's an example of changing the value of an entry in a HashMap
:
import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap that maps strings to integers HashMap<String, Integer> map = new HashMap<>(); // Add some entries to the map map.put("apple", 1); map.put("banana", 2); map.put("cherry", 3); // Print the map System.out.println(map); // prints {apple=1, banana=2, cherry=3} // Change the value of the entry with key "banana" map.put("banana", 4); // Print the map again System.out.println(map); // prints {apple=1, banana=4, cherry=3} } }