Java program to update value of hashmap using key
Sure, here's a Java program to update the value of a HashMap
using a key:
import java.util.HashMap; public class UpdateHashMapValue { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); System.out.println("Before update:"); System.out.println(map); String key = "B"; int newValue = 10; if (map.containsKey(key)) { map.put(key, newValue); } System.out.println("After update:"); System.out.println(map); } }
In this program, we first create a HashMap
map
with string keys and integer values. We then add some key-value pairs to the map using the put
method.
We then print out the map before updating the value.
We then define a string variable key
and an integer variable newValue
to represent the key and new value, respectively. We want to update the value of the key "B"
to 10
.
We then use an if
statement to check if the map contains the key "B"
. If it does, we use the put
method to update the value of "B"
to 10
.
Finally, we print out the map after updating the value.
Note that if the map does not contain the key "B"
, the put
method will add a new key-value pair to the map instead of updating an existing value. If you want to ensure that the key already exists before updating the value, you can use the containsKey
method to check for its existence first.