Reputation: 39
I have a requirement to modify certain elements inside a Groovy list based on a condition. For e.g.
def rowmbrs = [DW, PL01, ENT, ACCT]
I need to run a condition like - if one of the elements in the above list is PL01 then replace it with GL01. If you can give me a hint or some examples to achieve this requirement, that will be great. Thanks in advance.
Expected Result after running the logic
[DW, GL01, ENT, ACCT]
Upvotes: 2
Views: 10238
Reputation: 2255
You can use groovy style mapping function:
def rowmbrs = ['DW', 'PL01', 'ENT', 'ACCT']
rowmbrs.collect {
it == 'PL01' ? 'GL01' : it
}
or if you need to change only one element you can use the index of it's element:
rowmbrs[rowmbrs.indexOf('PL01')] = 'GL01'
Upvotes: 6
Reputation: 20707
if the order is not important:
def rowmbrs = ['DW', 'PL01', 'ENT', 'ACCT']
rowmbrs = rowmbrs - 'PL01' + 'GL01'
assert '[DW, ENT, ACCT, GL01]' == rowmbrs.toString()
Upvotes: 1