在嵌套列表中查找元素并进行转换(groovy)

时间:2016-05-31 09:43:22

标签: list groovy nested

如果我有一个Groovy嵌套列表,例如: List list = ['a', 'b', 'c', ['d', 'e', ['f']]]

我希望能够在列表中搜索特定元素,比如'd',然后将该元素转换为其他内容,例如['g','h'],以便新列表如下所示: ['a', 'b', 'c', [['g', 'h'], 'e', ['f']]]

2 个答案:

答案 0 :(得分:3)

喜欢这个??

List list = ['a', 'b', 'c', ['d', 'e', ['f']]]
assert list.collectNested{
    if (it == 'd') {
        ['g', 'h']
    } else {
        it
    }
} == ['a', 'b', 'c', [['g', 'h'], 'e', ['f']]]

答案 1 :(得分:0)

使用以下通用方法: -

def findAndReplace(def listValue, def listIndex, def valueToCompare, def valueToReplace, def originalList) {
    if(listValue instanceof List) {
        listValue.eachWithIndex { insideListValue, insideListIndex ->
                findAndReplace(insideListValue, insideListIndex, valueToCompare, valueToReplace, listValue)
      }
   }else if(listValue == valueToCompare) {
            originalList[listIndex] = valueToReplace
   }
}

List originalList = ['a', 'b', 'c', ['d', 'e', ['f']]]
def valueToCompare = 'd'
def valueToReplace =  ['g', 'h']
originalList.eachWithIndex { listValue, listIndex ->
    findAndReplace(listValue, listIndex, valueToCompare, valueToReplace, originalList)
}
println originalList

输出:[a, b, c, [[g, h], e, [f]]]

希望它会帮助你...... :)