Java HashMap put() Method
Last Updated :
20 Jan, 2025
Improve
The put() method of the Java HashMap class is used to add or update the key-value pairs in the map. If the key already exists in the map, the previous value associated with the key is replaced by the new value and If the key does not exist, the new key-value pair is added to the map.
Syntax of HashMap put() Method
public V put(K key, V value)
Parameters:
- Key: The key with which the specified value is associated.
- Value: The value to be associated with the specified key.
Return Types:
- If we add any duplicate key, the value associated with that key gets update and the previous value is replaced.
- When a new key is passes to the put() method, it is added to the map and the map returns “null”.
Example: The below Java program demonstrates the use of put() method to insert key-value pairs into the HashMap.
// Java program to demonstrate the
// working of HashMap put() method
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> hm = new HashMap<>();
// Add key-value pairs
hm.put("Java", 1);
hm.put("programming", 2);
hm.put("language", 3);
System.out.println("HashMap: " + hm);
}
}
Output
HashMap: {Java=1, language=3, programming=2}