Java HashMap put() Method
The put() method inserts the specified key/value pair into the HashMap.
The syntax for the put() method is:
hashmap.put(K key, V value)
Note: hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- value - the value
Return Value
If the key already exists, it replaces the existing value and returns the old value. If the key does not exist, it inserts the key/value pair and returns null.
Example
The following example demonstrates the use of the put() method when the key does not exist:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "tutorialpro");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
}
}
Executing the above program outputs:
HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
In the above example, we created a HashMap named sites and used the put() method to insert the key/value mappings into this HashMap.
To insert multiple key/value pairs, use the Java HashMap putAll() method.
Note: Each entry is inserted randomly into the HashMap.
Example of inserting when the key already exists:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "tutorialpro");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// Add a duplicate key element
String value = sites.put(1, "Weibo");
System.out.println("Modified HashMap: " + sites);
// Check the replaced value
System.out.println("Replaced value: " + value);
}
}
Executing the above program outputs:
Modified HashMap: {1=Weibo, 2=tutorialpro, 3=Taobao}
Replaced value: Google