Groovy:如何检查字符串是否包含数组的任何元素?

时间:2014-11-21 20:24:50

标签: arrays string groovy

我有一个字符串数组pointAddress,我想检查每个条目是否包含来自另一个数组的字符串validPointTypes

def pointAddress = ['bacnet://240101/AV:3', 'bacnet://240101/BV:9', 'bacnet://240101/AV:7', 'bacnet://240101/BALM:15']
def validPointTypes = ['AV', 'AI', 'AO', 'ANI', 'ANO', 'BV', 'BI', 'BO', 'BNI', 'BNO']

现在我只有一个巨大的if声明。

j = pointName.size()
for(j=j-1; j>=0;j--) {
    if(pointAddress[j]) {
        if(pointAddress[j].contains('AV') || pointAddress[j].contains('AI') || 
            pointAddress[j].contains('AO') || pointAddress[j].contains('ANI') || 
            pointAddress[j].contains('ANO') || pointAddress[j].contains('BV') || 
            pointAddress[j].contains('BI') || pointAddress[j].contains('BO') || 
            pointAddress[j].contains('BNI') || pointAddress[j].contains('BNO')) {
        } else {
            pointAddress.remove(j)
            pointName.remove(j)
            m++
        }
    } else {
        pointName.remove(j)
        m++
    }
}

必须有更好的方法,对吧?

1 个答案:

答案 0 :(得分:34)

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

应该这样做