Groovy - Remove keyvalue from map while iterating

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

http://stackoverflow.com/questions/7672262/remove-key-value-from-map-while-iterating/7672307#7672307 http://stackoverflow.com/questions/7672262/remove-key-value-from-map-while-iterating/7672307#7672307

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]

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/7672262/remove-key-value-from-map-while-iterating

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils