Iterating over and deleting from Hashtable in Java

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

    You can use Enumeration:

    Hashtable<Integer, String> table = ...
    
    Enumeration<Integer> enumKey = table.keys();
    while(enumKey.hasMoreElements()) {
        Integer key = enumKey.nextElement();
        String val = table.get(key);
        if(key==0 && val.equals("0"))
            table.remove(key);
    }
    
    0 讨论(0)
  • 2020-12-02 17:39

    You can use a temporary deletion list:

    List<String> keyList = new ArrayList<String>;
    
    for(Map.Entry<String,String> 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

    0 讨论(0)
  • 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<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();
      }
    }
    
    0 讨论(0)
  • 2020-12-02 17:49

    So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

     table.delete(key);
     for (K key: table.keySet()) {
        // do whatever you need to do with the rest of the keys
     }
    
    0 讨论(0)
提交回复
热议问题