Remove HashTable elements

We can remove elements from HashTable using methods provided in it

There are 2 methods listed below which can be used to remove elements from HashTable

Object remove(Object key)

Removes the mapping for the specified key from this HashTable if present.

Void clear()

Removes all of the mappings from this HashTable

Example

  1. import java.util.*;
  2. public class HashTableRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5.  Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>();
  6.       hashTable.put(1, "One");
  7.       hashTable.put(2, "Two");
  8.       hashTable.put(3, "Three");
  9. System.out.println("Initial HashTable");
  10. System.out.println(hashTable);
  11.  
  12. hashTable.remove(1);
  13. System.out.println("HashTable after removing 1 element");
  14. System.out.println(hashTable);
  15.  
  16. hashTable.clear();
  17. System.out.println("HashTable after removing all elements");
  18. System.out.println(hashTable);
  19.  
  20. }
  21. }
import java.util.*;
public class HashTableRemoveExample {
public static void main(String args[]) {

 Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>(); 
      hashTable.put(1, "One");
      hashTable.put(2, "Two");
      hashTable.put(3, "Three");
System.out.println("Initial HashTable");
System.out.println(hashTable);

hashTable.remove(1);
System.out.println("HashTable after removing 1 element");
System.out.println(hashTable);

hashTable.clear();
System.out.println("HashTable after removing all elements");
System.out.println(hashTable);

}
}


We can see that, clear() method has removed all elements in HashTable and remove() method has removed only specified element from the HashTable.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on