Laurie Hirsch
Laurie Hirsch

Reputation: 3

Find element in a nested list and transform (groovy)

If I have a Groovy nested list such as: List list = ['a', 'b', 'c', ['d', 'e', ['f']]]

I would like to be able to search the list for a particular element, say 'd' and then transform that element to something else such as ['g', 'h'] so that the new list looks like: ['a', 'b', 'c', [['g', 'h'], 'e', ['f']]]

Upvotes: 0

Views: 1112

Answers (2)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

Use following generic approach :-

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

Output: [a, b, c, [[g, h], e, [f]]]

Hope it will help you...:)

Upvotes: 0

koji
koji

Reputation: 179

Like this??

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']]]

Upvotes: 4

Related Questions