Java HashMap replace() Method
Example
Replace the values of entries in a map:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "Cambridge");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
capitalCities.replace("England", "London");
capitalCities.replace("Canada", "Ottawa");
capitalCities.replace("USA", "New York", "Washington DC");
System.out.println(capitalCities);
}
}
Definition and Usage
The replace()
method writes a new value to an existing entry in the map. The entry can be specified by its key, or by both its key and value.
Syntax
One of the following:
public V replace(K key, V newValue)
public boolean replace(K key, V oldValue, V newValue)
K
and V
refer to the data types of the keys and values of the map.
Parameter Values
Parameter | Description |
---|---|
key | Required. The key of the entry to be removed. |
oldValue | Optional. The value of the entry to be removed. |
newValue | Required. The value to write into the entry. |
Technical Details
Returns: |
When the oldValue argument is specified, it returns true if the entry was replaced and false otherwise.If the oldValue argument is not specified then it returns the value that the entry had before it was replaced, or null if an entry with the specified key does not exist. |
---|
Related Pages
❮ HashMap Methods