What is put in Java HashMap?

The put function is used to insert a new key-value pair into a HashMap. We insert a key and its corresponding value into the map.

If the key already exists, its old value is replaced with a new one.

Parameters

java.util.HashMap.put(K key, V value)

In the above snippet of code, key is the key stored on the map, and this key recognizes the entity in the map. Value is the value that will be stored that corresponds to the key.

The data types of K and V are determined while the HashMap is being declared.

Return value

If a new pair is added to the HashMap, the put function returns NULL.

If the key is already present in the HashMap, its value gets updated, and the put function returns the previous value.

Example

import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
// making a hashmap with keys as integers and strings as corresponding values
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
hash_map.put(10, "Ten");
hash_map.put(20, "Twenty");
hash_map.put(30, "Thirty");
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
// using the put function with an existing key
String returned_value = (String)hash_map.put(20, "Forty");
// displaying the value returned by using existing key with put function
System.out.println("Value Returned by Using put function with existing key: " + returned_value);
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
}
}

In the above example, we created a HashMap with three values, initially.

Then, we updated the value of an existing key using the put method and stored the returned value in a variable. This returned value is the previous value of that key.

Moreover, we can also see that using the put function with an existing key replaces its old value with the new value in the map. This change can be observed by the state of the HashMap in the output above.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved