Home > Back-end >  Groovy: Parsing List elements
Groovy: Parsing List elements

Time:09-20

For learning purpose, I like to parse the following look up table as follows: I want to check the branch name and fetch the corresponding name value, but i want to do fetch first name of each branch, like : [branch: "test"] => name "a" than [branch: "test-1"] => name "d" ; and so on,

LUT = [
    [branch: "test", name: 'a', image_name: 'abc'],
    [branch: "test", name: 'b', image_name: 'abc'],
    [branch: "test", name: 'c', image_name: 'abc'],
    [branch: "test-1", name: 'd', image_name: 'abc'],
    [branch: "test-1", name: 'e', image_name: 'abc'],
    [branch: "test-2", name: 'f', image_name: 'abc'],
    [branch: "test-2", name: 'g', image_name: 'abc'],
    [branch: "test-2", name: 'h', image_name: 'abc'],
    [branch: "test-3", name: 'i', image_name: 'abc'],
    [branch: "test-3", name: 'j', image_name: 'abc'],
    [branch: "test-4", name: 'k', image_name: 'abc'],
    [branch: "test-5", name: 'l', image_name: 'abc'],
]

for example the result may look like:

result = {
 "test": [{ "name":"a" }],
 "test-1": [{ "name":"d" }],
 "test-2": [{ "name":"f" }],
 "test-3": [{ "name":"i" }], 
"test-4": [{ "name":"k" }], 
"test-5": [{ "name":"l" }], 
} 

Also, later on i may like to add additional values to the keys for example in test-1: "test-1": [{ "name":"a", "new_name":"new" }]

CodePudding user response:

Not positive how to format the result like you want it but finding the first instance of each branch is fairly easy.

result = [:]
for (map in LUT)
{
    if (!result.containsKey(map['branch']))
    {
        println map['name'] // prints the unique name
        result.put(map['branch'], map['name'])
    }
}
  • Related