在迭代时从地图中删除键/值 [英] Remove key/value from map while iterating

查看:117
本文介绍了在迭代时从地图中删除键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个这样的地图:

  def myMap = [:] 

地图基本上是一个键的对象,一个int的值。当我迭代地图时,我解释这个值,如果是0,我删除它。我已经尝试过 myMap.remove(),但是我得到一个 ConcurrentModificationError - 这是很公平的。所以我继续使用 it.remove(),这是给我奇怪的结果。



基本上,我的代码是这样的:

  myMap.each {
it.value--;

if(it.value< = 0)
it.remove();
}

足够简单。我的问题是,如果我在删除之前和之后打印 myMap.size(),它们是一样的。如果我调用 myMap.containsKey(key),它会给我 true ,关键还在那里。 p>

但是,如果我打印出这样的地图:

 code> myMap.each {System.out.println($ it.key:$ it.value); 

我什么都没有,调用 myMap.keySet() myMap.values()返回空。



任何人都知道发生了什么? >

解决方案

这应该比 Tim的答案(因为你只需要遍历地图一次)。不幸的是,它也是相当冗长的

  def map = [2:1,3:4] 
def iterator = map.entrySet()。iterator()

while(iterator.hasNext()){

if(iterator.next()。value - 1 <= 0) {
iterator.remove()
}
}

//测试它工作
assert map == [3:4]


I'm creating a map like this:

def myMap = [:]

The map is basically an object for a key and an int for a value. When I iterate over the map, I decret the value, and if it's 0, I remove it. I already tried myMap.remove(), but I get a ConcurrentModificationError - which is fair enough. So I move on to using it.remove(), which is giving me weird results.

Basically, my code is this:

myMap.each {
    it.value--;

    if( it.value <= 0 )
        it.remove();
}

Simple enough. My problem is, if I print myMap.size() before and after the remove, they're the same. If I call myMap.containsKey( key ), it gives me true, the key is still in there.

But, if I print out the map like this:

myMap.each { System.out.println( "$it.key: $it.value" ); }

I get nothing, and calling myMap.keySet() and myMap.values() return empty.

Anyone know what's going on?

解决方案

This should be a bit more efficient than Tim's answer (because you only need to iterate over the map once). Unfortunately, it is also pretty verbose

def map = [2:1, 3:4]
def iterator = map.entrySet().iterator()

while (iterator.hasNext()) {

  if (iterator.next().value - 1 <= 0) {
    iterator.remove()
  }
}

// test that it worked
assert map == [3:4]

这篇关于在迭代时从地图中删除键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆