Search code examples
groovy

How to add a numerator to each sub-collection of a multilevel collection?


I have this collection

[
    [Name:John, City:London],
    [Name:Rachel, City:Paris]
]

I want to add a numerator to each sub-collection so that the result will be

[
    [Number:1, Name:John, City:London],
    [Number:2, Name:Rachel, City:Paris]
]

I know of eachWithIndex() but it adds the numerator outside of the subcollection.

I would appreciate any idea.

Thanks!


Solution

  • Essentially a one-liner:

    def list = [     [Name:'John', City:'London'],     [Name:'Rachel', City:'Paris'] ]
    
    def res = list.indexed().collect{ num, v -> v + [ Number:num + 1 ] }
    
    assert res.toString() == '[[Name:John, City:London, Number:1], [Name:Rachel, City:Paris, Number:2]]'