Skip to content

Clear or Remove All Entries from Hashtable in Java Example

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.

The hashtable object becomes empty after this method call.

Output

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.

Output

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

About the author

Leave a Reply

Your email address will not be published.