• Java Data Structures Tutorial

Remove elements from a hash table



You can remove elements of the hash table you can use the remove() method of the HashTable class.

To this method you need to pass either key or key-value pair to delete the required element.

hashTable.remove("Ram");
or
hashTable.remove("Ram", 94.6);

Example

import java.util.Hashtable;

public class RemovingElements {
   public static void main(String args[]) {
      Hashtable hashTable = new Hashtable();
      hashTable.put("Ram", 94.6);
      hashTable.put("Rahim", 92);
      hashTable.put("Robert", 85);
      hashTable.put("Roja", 93);
      hashTable.put("Raja", 75);

      System.out.println("Contents of the hash table :"+hashTable); 
      hashTable.remove("Ram");
      System.out.println("Contents of the hash table after deleting the specified elements :"+hashTable); 
   }
}

Output

Contents of the hash table :{Rahim = 92, Roja = 93, Raja = 75, Ram = 94.6, Robert = 85}
Contents of the hash table after deleting the specified elements :{Rahim = 92, Roja = 93, Raja = 75, Robert = 85}
Advertisements