Write a Java program to Checking duplicate key insertion in HashMap


In this program, a HashMap named "h" is created using the syntax: HashMap h = new HashMap<>(); Next, 5 key-value pairs are added to the HashMap using the put() method. The keys are integers and the values are strings. Note that the second entry has a key of 11, which is duplicated in the third entry.

Then, the entrySet() method of the HashMap is used in a for-each loop to iterate through the key-value pairs in the HashMap. For each pair, the key and value are printed to the console using the getKey() and getValue() methods of the Map.Entry object.

When the program is executed, the output shows that the key-value pair with the key 11 appears only once in the HashMap. This is because HashMap does not allow duplicate keys. When a duplicate key is added, the value associated with the original key is overwritten with the new value. In this case, the value associated with the key 11 is "Kumar" and not "Sathish".

Source Code

import java.util.*;
public class Checking_Duplicate
{
	public static void main(String args[])
	{
		HashMap<Integer,String> h =new HashMap<>();
		h.put(10,"Sam");
		h.put(11,"Sathish");
		h.put(11,"Kumar");//adding element with duplicate key
		h.put(12,"Ram"); 
		h.put(13,"Pooja");
 
		for(Map.Entry e : h.entrySet())
		{
			System.out.println("Key : "+ e.getKey());
			System.out.println("Value : "+e.getValue());
		}
	}
}

Output

Key : 10
Value : Sam
Key : 11
Value : Kumar
Key : 12
Value : Ram
Key : 13
Value : Pooja