📜  java hashmap replace - Java (1)

📅  最后修改于: 2023-12-03 14:42:14.361000             🧑  作者: Mango

Java HashMap replace

HashMap is a class in Java that implements the Map interface to store key-value pairs. The replace method in HashMap is used to replace the value mapped by a key with a new value.

Syntax

The general syntax of the replace method in HashMap is:

public V replace(K key, V value)

where key is the key whose value is to be replaced with the new value. The method returns the previous value associated with the key, or null if the key is not in the HashMap.

Example

Consider the following example where we want to replace the value associated with the key "name" in a HashMap<String, String>.

HashMap<String, String> map = new HashMap<>();
map.put("name", "John");
map.put("age", "25");

// Replace the value associated with key "name"
String oldValue = map.replace("name", "Smith");
System.out.println("Old value: " + oldValue); // Output: Old value: John
System.out.println("New value: " + map.get("name")); // Output: New value: Smith

In this example, we first create a HashMap<String, String> with two key-value pairs, "name" -> "John" and "age" -> "25". Then we call the replace method on the HashMap with the key "name" and the new value "Smith". The method returns the old value "John" which we print to the console. Finally, we print the new value associated with the key "name", which is now "Smith".

Conclusion

In conclusion, the replace method in HashMap is a useful method to replace the value associated with a key in a HashMap. It can be called on any HashMap object and takes a key parameter and a value parameter. It returns the old value associated with the key or null if the key is not in the HashMap.