Remove key / value from map during iteration

I create a map like this:

def myMap = [:] 

A map is basically an object for a key and an int for a value. When I iterate over the map, I decrease the value, and if it is 0, I delete it. I already tried myMap.remove() , but I got a ConcurrentModificationError - this is fair enough. So I move on to using it.remove() , which gives me weird results.

Basically, my code is this:

 myMap.each { it.value--; if( it.value <= 0 ) it.remove(); } 

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

But, if I print the card as follows:

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

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

Does anyone know what is going on?

+6
source share
2 answers

This should be a little more efficient than Tim's answer (because you only need to repeat on the map once). Unfortunately, this is also quite 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] 
+10
source

Can you do something like this:

 myMap = myMap.each { it.value-- }.findAll { it.value > 0 } 

This subtracts the value from each value, and then returns a new map of only those records where the value is greater than zero.

You should not call the remove method on the Entry card, it should be a private method used inside the card ( see line 325 for implementing Java 7 ), so you yourself call it a closing card in all kinds of cases (she does not know that she is playing records) .

Groovy allows you to call private methods, so you can do this kind of cheating behind the back of Java classes

Edit - Iterator Method

Another way:

 myMap.iterator().with { iterator -> iterator.each { entry -> entry.value-- if( entry.value <= 0 ) iterator.remove() } } 
+6
source

Source: https://habr.com/ru/post/898741/


All Articles