Iterating over and deleting from Hashtable in Java

前端 未结 4 956
温柔的废话
温柔的废话 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:39

    You can use a temporary deletion list:

    List keyList = new ArrayList;
    
    for(Map.Entry entry : hashTable){
      if(entry.getValue().equals("delete")) // replace with your own check
        keyList.add(entry.getKey());
    }
    
    for(String key : keyList){
      hashTable.remove(key);
    }
    

    You can find more information about Hashtable methods in the Java API

提交回复
热议问题