English 中文(简体)
拆除地图上的关键/价值,同时重新定位
原标题:Remove key/value from map while iterating

我制定这样一个地图:

def myMap = [:]

地图基本上是一个关键和具有价值的物体。 当我篡改地图时,我删除了价值,如果是零,我就删除。 我已经尝试了myMap.remove(),但我收到了一份<编码>目前版本的英文/法文>,该编码足够公允。 因此,我开始使用<代码>it.remove(),这给我带来了令人难忘的结果。

基本上,我的法典就是:

myMap.each {
    it.value--;

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

足够简单。 我的问题是,如果我在拆除之前和之后印刷<密码>my.size(),那么,他们就照此办理。 如果我打电话myMap.containsKey(钥匙),则该钥匙仍留在该地。

But,如果我照此打印:

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

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

谁知道正在发生什么?

最佳回答

这比。 时间回答(因为你只需要一度地绘制地图)。 不幸的是,它也是粗略的。

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]
问题回答




相关问题
Which name for a "smart" dictionary (hashtable)?

I m looking for a good name for a custom dictionary which automatically initializes the value for a requested key if it doesn t exist, using a delegate. The indexer implementation should help ...

Using Classes in a Dictionary in Classic ASP

I usually do C# but have inherited a classic ASP project. I have defined a class: Class clsPayment Public Name End Class Set objPayment = New clsPayment objPayment.Name = "...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

Python dictionary simple way to add a new key value pair

Say you have, foo = bar d = { a-key : a-value } And you want d = { a-key : a-value , foo : bar } e = { foo :foo} I know you can do, d[ foo ] = foo #Either of the following for e e = { foo :foo}...

Storing ints in a Dictionary

As I understand, in Objective-C you can only put Objects into dictionaries. So if I was to create a dictionary, it would have to have all objects. This means I need to put my ints in as NSNumber, ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签