简体   繁体   中英

removing a specific value from a groovy list

I have my code snippet as below, and I would like to ignore/remove the value from the list in the else part of the condition check. offerRecords.remove(tariffOffer) doesnt seem to work

offerRecords.each { tariffOffer ->

    handsetData.each { hs ->
        if (tariffOffer.HANDSET_BAND.stringValue() == hs.HANDSET_BAND?.stringValue()) {
            //println 'condition is satisfied and set the handset id ****** '
            handset.add(hs.HANDSET_PKEY_ID?.stringValue())
        }

        if (handset.size() > 0) {
            // need to call a method
            recHandset = applyHandsetRulesCHL(tariffOffer, handset)
        }
        else {
            // ignore/remove the tariffOffer
            offerRecords.remove(tariffOffer) // i know it doesn't serve the purpose
        }

Just filter your list before process:

def filteredList = handsetData.findAll{handset.size() > 0}

and process filtered result. By the way, I can't understand what is handset in each{} body, but I guess you got the idea.

This is typical java concurrent modification.

ie You can't modify a list while iterating over it.

In addition to Mr. Cat's earlier suggestion of filtering the data prior to iteration, there are many solutions depending on other factors of your use case, see This SO question .

One example would be to keep a parallel list of invalid entries, then remove them from the original list once iteration is complete:

def listToTest = ['a', 1, 'b', 'c']

def invalidItems = []
listToTest.each {
    if (it == 1)
        invalidItems << it
}

listToTest.removeAll invalidItems

assert ['a', 'b', 'c'] == listToTest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM