This example shows how to clear or remove all entries from the Hashtable in Java. The example also shows how to clear or remove all entries using the clear method and iterator.
How to clear or remove all mappings from the Hashtable in Java?
There is a couple of ways using which we can remove all the mappings from the hashtable as given below.
1. Using the clear method
The Hashtable clear
method removes all the entries from the hashtable object.
1 |
public void clear() |
The hashtable object becomes empty after this method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Hashtable; public class HashtableClearExample { 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("Is empty? " + hashtable.isEmpty()); /* * To remove all the entries or * clear the hashtable, use the clear method */ hashtable.clear(); //this will return true now System.out.println("Is empty? " + hashtable.isEmpty()); } } |
Output
1 2 |
Is empty? false Is empty? true |
Please also visit how to check if hashtable is empty example to know more.
2. Using the iterator
We can get all the entries or mappings from the hashtable object using the entrySet
method. Once we get the Set view of all the entries, we can obtain an iterator from it using the iterator
method.
We can remove the hashtable entries while iterating using the remove
method of the iterator as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); System.out.println("There are " + hashtable.size() + " mappings"); //get iterator for entry set Iterator<Map.Entry<Integer, String>> itr = hashtable.entrySet().iterator(); while( itr.hasNext() ){ itr.next(); //use remove method of the iterator itr.remove(); } //this will return 0 now System.out.println("There are " + hashtable.size() + " mappings"); |
Output
1 2 |
There are 3 mappings There are 0 mappings |
Instead of iterating the hashtable entries, we can also get all keys of the hashtable using the keySet
method and remove the entries using its iterator.
This example is a part of the Java Hashtable Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Hashtable Documentation