In Java 8, you can use the getOrDefault() method in conjunction with the put() method to update the value for a given key in a HashMap.
Here's an example:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map hashMap = new HashMap<>();
// Adding initial key-value pairs
hashMap.put("Key1", 1);
hashMap.put("Key2", 2);
hashMap.put("Key3", 3);
System.out.println("HashMap before update: " + hashMap);
// Updating the value for a given key using getOrDefault() and put()
String keyToUpdate = "Key2";
int newValue = 10;
int oldValue = hashMap.getOrDefault(keyToUpdate, 0);
hashMap.put(keyToUpdate, newValue);
System.out.println("HashMap after update: " + hashMap);
}
}
In this example, we create a HashMap called hashMap to store key-value pairs. We add three initial key-value pairs using the put() method. Then, we print the hashMap before the update.
To update the value for a given key, we specify the key to update (keyToUpdate) and the new value (newValue). We use getOrDefault(key, defaultValue) to retrieve the current value associated with the key. If the key is present, it returns the current value; otherwise, it returns the specified default value (0 in this case). We store the old value in oldValue variable.
Next, we use the put(key, value) method to update the value for the given key. We provide the keyToUpdate and newValue as arguments. If the key is already present in the map, the value will be updated; otherwise, a new key-value pair will be added.
Finally, we print the updated hashMap. The output of this example will be:
HashMap before update: {Key1=1, Key2=2, Key3=3}
HashMap after update: {Key1=1, Key2=10, Key3=3}
As you can see, the value for the key "Key2" is updated from 2 to 10 in the HashMap.
No comments:
Post a Comment