Java HashMap put(K key, V value) Example

The put(K key, V value) method of java.util.HashMap class associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Signature

public V put(K key, V value)

This method associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Example

The following example shows the usage of java.util.HashMap.put(key,value) method.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class PutMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
    
        //Print the elements of the hashMap1
        Iterator it = hashMap1.entrySet().iterator();
        while(it.hasNext())
        {
            Map.Entry entry = (Map.Entry) it.next();
            System.out.print("Key : "+entry.getKey());
            System.out.println("  Value : "+entry.getValue());
        }
    } 
}

Output

Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5

Leave a Reply

Your email address will not be published. Required fields are marked *