Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over and deleting from Hashtable in Java

I have a Hashtable in Java and want to iterate over all the values in the table and delete a particular key-value pair while iterating.

How may this be done?

like image 224
Mohit BAnsal Avatar asked Feb 28 '10 14:02

Mohit BAnsal


People also ask

How do you remove a mapping while iterating over HashMap in Java?

You should always use Iterator's remove() method to remove any mapping from the map while iterating over it to avoid any error.

How do I remove an item from a Hashtable in Java?

Hashtable remove() Method in Java remove() is an inbuilt method of Hashtable class and is used to remove the mapping of any particular key from the table. It basically removes the values for any particular key in the Table. Parameters: The method takes one parameter key whose mapping is to be removed from the Table.

Can we remove elements from HashMap while iterating?

While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry. getKey() method. If the key matches, remove the entry of that iteration from the HashMap using remove() method.


1 Answers

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...  Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();  while (it.hasNext()) {   Map.Entry<Integer, String> entry = it.next();    // Remove entry if key is null or equals 0.   if (entry.getKey() == null || entry.getKey() == 0) {     it.remove();   } } 
like image 108
Adamski Avatar answered Sep 22 '22 07:09

Adamski