Search code examples
javagroovyeachlinkedhashmapconcurrentmodification

Concurrent exception in Groovy even when changes are made to another LinkedHashMap


I have created a new LinkedHashMap 'workingStrData' using 'strData' and I still get the error.

I am trying to remove some items from this LinkedHashMap based of another list.

The way strData is structured is

    strData = [components[{key1:value1}{key2:value2}...]]     

    def workingStrData = new LinkedHashMap(strData)
    List componentsToRemove = ['item1','item2'...]
    int itemsRemoved = 0

    workingStrData.components.eachWithIndex {
            comp, workingStrIndex ->
                println("Index: "+workingStrIndex+" Component: "+comp.number)

                def baditem = comp.number in componentsToRemove
                if (baditem) {
                    strData.components.remove(workingStrIndex - itemsRemoved)
                    itemsRemoved += 1
                }
        }

Solution

  • You cannot remove an element from a list while iterating with each or with eachWithIndex which by the way is a bad practice. Groovy offers much more elegant and simpler solutions.

    As suggested, try retainAll() or as suggested here, try removeAll():

    def strData = [
        components : [
            [number: 'item0'],
            [number: 'item1']
        ]
    ]
    
    def componentsToRemove = [
        'item1','item2'
    ]
    
    componentsToRemove.each { removeIt ->
        strData.components.removeAll { it.number == removeIt }
    }
    
    assert strData.components == [[number: 'item0']]