【问题标题】:Delete an entry in hashmap while iterating迭代时删除哈希图中的条目
【发布时间】:2020-05-17 19:48:43
【问题描述】:

我有一个循环来迭代哈希图。如果满足条件,我需要从哈希图中删除键值对。我无法使用下面的代码来做到这一点。我怎样才能做到这一点?

for(HashMap.Entry<Integer,Character> m:commons.entrySet()){
    while(i!=(int)m.getKey()){
        i++;
    }
    if(s2.charAt(i)!=(int)m.getKey()){
      commons.remove((int)m.getKey());
    }
}

【问题讨论】:

  • 你能显示完整的代码吗? i 变量从何而来?

标签: java hashmap iteration remove-if


【解决方案1】:
for (Iterator<Map.Entry<Integer, Character>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<Integer, Character> entry = it.next();

    // casting to int is redundant in your code. I removed it.
    while (i != entry.getKey()) i++;

    if (s2.charAt(i) != entry.getKey()) {
        it.remove();
    }
}

您可以在迭代Map 时使用Iterator 安全删除。

您也可以查看.removeIf() (Java 8+),但在您的迭代中使用循环,这更具可读性,imo。

【讨论】:

  • 谢谢哈沙尔。现在说得通了
【解决方案2】:
  1. 您尝试这样做的方式可能会导致ConcurrentModificationException。您应该使用 IteratorCollection::removeIf,它们在内部使用 Iterator
  2. 虽然您可以将charint 进行比较,但您可能在比较中混淆了键和值。你写了

    if(s2.charAt(i)!=(int)m.getKey())
    

    您将s2.charAt(i)Integer 的键进行比较。从语法上讲,它是正确的,但您可能想比较该值(这是一个 Characater),即您很可能想要这样做

    if(s2.charAt(i)!=(int)m.getValue())
    

按如下方式进行:

for (Iterator<Entry<Integer, Character>> itr = commons.entrySet().iterator(); itr.hasNext();) {
    Entry<Integer, Character> entry = itr.next();

    while (i != entry.getKey()) {
        i++;
    }

    if (s2.charAt(i) != entry.getValue()) {
        itr.remove();
    }
}

【讨论】:

  • 谢谢阿文德。这个概念现在对我来说更清楚了
  • 我希望该解决方案对您有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。
猜你喜欢
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2015-04-30
  • 2011-04-28
  • 2012-12-27
相关资源
最近更新 更多