Remove duplicate key from hashtable - Java Program

Q. Write a program to remove duplicate key from hashtable.

Answer:

Below example shows how to use the user defined function to remove the duplicate keys from the list. We have to implement equals and hashcode methods.

Students.java

class Students
{
    private String name;
    private int reg_No;
    private int roll;
     
    public Students(int roll, String n, int s)
    {
        this.roll = roll;
        this.name = n;
        this.reg_No = s;
    }     
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getreg_No()
    {
        return reg_No;
    }
    public void setreg_No(int reg_No)
    {
        this.reg_No = reg_No;
    }
    public String toString()
    {
        return "roll: "+this.roll+", Name: "+this.name+", Registration_No: "+this.reg_No;
    }
    public void setroll(int roll)
    {
        this.roll = roll;
    }
    public int getroll()
    {
        return roll;
    }     
    @Override
    public int hashCode()
    {
        System.out.println("In hashcode method");
        return this.getroll();
    }     
    @Override
    public boolean equals(Object obj)
    {
        Students stud = null;
        if(obj instanceof Students)
        {
            stud = (Students) obj;
        }
        System.out.println("In equals methods");
        if(this.getroll() == stud.getroll())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


HashtableDupEntry.java

import java.util.Hashtable;
import java.util.Set;

public class HashtableDupEntry
{
    public static void main(String a[])
    {

        Hashtable<Students,String> tm = new Hashtable<Students, String>();
        tm.put(new Students(101,"Ram",81101), "RAM");
        tm.put(new Students(121,"Ravi",82121), "RAVI");
        tm.put(new Students(110,"Atul",83110), "ATUL");
        tm.put(new Students(102,"Anil",81102), "ANIL");
        System.out.println("Adding duplicate entry:");
        tm.put(new Students(102,"Anil",81102), "ANIL");
        System.out.println("Hashtable entries:");
        Set<Students> keys = tm.keySet();
        for(Students key:keys)
        {
            System.out.println(key+" ==> "+tm.get(key));
        }
        System.out.println("Duplicate keys eliminated!!!");
    }
}


Output:

duplicate key hashtable