Iterating over and deleting from Hashtable in Java

前端 未结 4 945
温柔的废话
温柔的废话 2020-12-02 16:56

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?

4条回答
  •  时光取名叫无心
    2020-12-02 17:47

    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 map = ...
    
    Iterator> it = map.entrySet().iterator();
    
    while (it.hasNext()) {
      Map.Entry entry = it.next();
    
      // Remove entry if key is null or equals 0.
      if (entry.getKey() == null || entry.getKey() == 0) {
        it.remove();
      }
    }
    

提交回复
热议问题