Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a specific element in a Groovy list

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]
like image 818
Vikas Avatar asked Sep 14 '26 04:09

Vikas


1 Answers

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'​​​​​​​​​​​​​​​​​
like image 162
Uladzislau Kaminski Avatar answered Sep 17 '26 07:09

Uladzislau Kaminski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!