Home > Software design >  Create a list with updated values of only certain keys inside a given list of maps in groovy
Create a list with updated values of only certain keys inside a given list of maps in groovy

Time:08-07

I have this list of maps:

[
[a:1998-01-14, b:2028-11-05, c:OQSeMPIcHNP, d:ASD, e:DEF, f:UuzSJiVvxjhJipzxUPsSsbmaeMvOT, g:mef, e:P00003036, h:P], 
[a:1998-08-22, b:2028-11-05, c:fDScShsqpKqreHPqpANUrnZklN, d:LAS, e:FGH, f:lKuMgRxxrVuwCEXMNiIERHOcUCNmbG, g:ela, e:P00006583, h:P], 
[a:1992-02-29, b:2031-01-01, c:SOThmQNAbKexnvDaxOi, d:MAR, e:ZAD, f:tkYiSUxSoTZrceRoIOYYsZztvvnzkno, g:ela, e:P00002839, h:P]
]

I need to create a new list of maps or update the existing one by doing a uppercase on all the values of all the keys c and f.

Expected outcome:

[
[a:1998-01-14, b:2028-11-05, c:OQSEMPICHNP, d:ASD, e:DEF, f:UUZSJIVVXJHJIPZXUPSSSBMAEMVOT, g:mef, e:P00003036, h:P], 
[a:1998-08-22, b:2028-11-05, c:FDSCSHSQPKQREHPQPANURNZKLN, d:LAS, e:FGH, f:LKUMGRXXRVUWCEXMNIIERHOCUCNMBG, g:ela, e:P00006583, h:P], 
[a:1992-02-29, b:2031-01-01, c:SOTHMQNABKEXNVDAXOI, d:MAR, e:ZAD, f:TKYISUXSOTZRCEROIOYYSZZTVVNZKNO, g:ela, e:P00002839, h:P]
]

How can I achieve this with groovy?

CodePudding user response:

Please try this:

def source = [
    [a:'1998-01-14', b:'2028-11-05', c:'OQSeMPIcHNP', d:'ASD', e:'DEF', f:'UuzSJiVvxjhJipzxUPsSsbmaeMvOT', g:'mef', e1:'P00003036', h:'P'],
    [a:'1998-08-22', b:'2028-11-05', c:'fDScShsqpKqreHPqpANUrnZklN', d:'LAS', e:'FGH', f:'lKuMgRxxrVuwCEXMNiIERHOcUCNmbG', g:'ela', e1:'P00006583', h:'P'],
    [a:'1992-02-29', b:'2031-01-01', c:'SOThmQNAbKexnvDaxOi', d:'MAR', e:'ZAD', f:'tkYiSUxSoTZrceRoIOYYsZztvvnzkno', g:'ela', e1:'P00002839', h:'P']
]

def target = source.collect {
    it.c = it.c?.toUpperCase()
    it.f = it.f?.toUpperCase()
    it
}

println "target = $target"
  • Related