[英]removing a specific value from a groovy list
我的代码片段如下,并且我想忽略/从条件检查的else部分中的列表中删除该值。 offerRecords.remove(tariffOffer)似乎不起作用
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
}
只需在处理之前过滤列表:
def filteredList = handsetData.findAll{handset.size() > 0}
并处理过滤后的结果。 顺便说一句,我无法理解each{}
机身中的handset
是什么,但我想您已经明白了。
这是典型的Java并发修改。
即您不能在迭代列表时修改列表。
除了Cat先生较早提出的在迭代之前过滤数据的建议外,还有许多解决方案,具体取决于您的用例的其他因素,请参阅此SO问题 。
一个示例是保留无效条目的并行列表,然后在迭代完成后将它们从原始列表中删除:
def listToTest = ['a', 1, 'b', 'c']
def invalidItems = []
listToTest.each {
if (it == 1)
invalidItems << it
}
listToTest.removeAll invalidItems
assert ['a', 'b', 'c'] == listToTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.