Last Updated : 11 Jul, 2025
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() Methodpublic V put(K key, V value)
Parameters:
Return Types:
Example: The below Java program demonstrates the use of put() method to insert key-value pairs into the HashMap.
Java
// 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);
}
}
HashMap: {Java=1, language=3, programming=2}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4