繁体   English   中英

迭代时删除 hashmap 中的一个条目

[英]Delete an entry in hashmap while iterating

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

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());
    }
}
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。

  1. 您尝试执行此操作的方式可能会导致ConcurrentModificationException 您应该使用内部使用IteratorIteratorCollection::removeIf
  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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM