YouTip LogoYouTip

Java Hashmap Put

# Java HashMap put() Method [![Image 3: Java HashMap](#) Java HashMap](#) 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 value corresponding to the inserted key already exists, a value replacement operation is performed, and the old value is returned. If it does not exist, an insertion is performed, and null is returned. ### Example The following example demonstrates the use of the put() method (when the value corresponding to the key does not exist): ## Example import java.util.HashMap; class Main { public static void main(String[] args){ // Create a HashMap HashMap sites =new HashMap(); // Add some elements to the HashMap sites.put(1, "Google"); sites.put(2, ""); sites.put(3, "Taobao"); System.out.println("HashMap: "+ sites); } } The output of the above program is: HashMap: {1=Google, 2=, 3=Taobao} In the above example, we created a HashMap named `sites`. The code later used the `put()` method to insert this key/value mapping into the HashMap. Insert multiple key/value pairs using the [Java HashMap putAll() method](#). **Note:** Each item is inserted randomly into the HashMap. Example where the value corresponding to the key already exists: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ // Create a HashMap HashMap sites =new HashMap(); // Add some elements to the HashMap sites.put(1, "Google"); sites.put(2, ""); 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); // View the replaced value System.out.println("Replaced value: "+ value); } } The output of the above program is: Modified HashMap: {1=Weibo, 2=, 3=Taobao}Replaced value: Google [![Image 4: Java HashMap](#) Java HashMap](#)
← Python3 Os ChmodPython3 Os File Methods β†’