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.
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.
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.
import java.util.*;class HelloWorld {public static void main( String args[] ) {// making a hashmap with keys as integers and strings as corresponding valuesHashMap<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 HashMapSystem.out.println("Hash Map: " + hash_map);// using the put function with an existing keyString returned_value = (String)hash_map.put(20, "Forty");// displaying the value returned by using existing key with put functionSystem.out.println("Value Returned by Using put function with existing key: " + returned_value);// displaying the HashMapSystem.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