'Transforming list to map in Groovy

I'm trying to transform a list of strings:

def description = """user:[email protected];groups:Team-1, Team-2
user:[email protected];groups:Team-2, Team-3
user:[email protected];groups:Team-1, Team-3
some other text"""

description = description.split('\\r\\n|\\n|\\r').findAll { it.startsWith('user') }

into a map so it looked like this:

[[email protected]: "Team-2, Team-3", [email protected]: "Team-2, Team-3", [email protected]: "Team-1, Team-3"]

so I could later iterate getting an e-mail address and corresponding teams.

Sadly with the below code I was only able to partly achieve it and only for one item of the list. I'm stuck with getting it into a loop and get the full result.

def userData = [:]
userData = description[0].split(';').inject([:]) { map, token ->
    token.split(':').with {
        map[it[0].trim()] = it[1].trim()
    }
    map
}

Can you give me a hint as for how I could get a map with all the items from the list?



Solution 1:[1]

You can use collectEntries method on a list:

def description = """user:[email protected];groups:Team-1, Team-2
user:[email protected];groups:Team-2, Team-3
user:[email protected];groups:Team-1, Team-3
some other text"""

description = description.split('\\r\\n|\\n|\\r').findAll { it.startsWith('user') }

def map = description.collectEntries {
    // split "user:[email protected];groups:Team-1, Team-2"
    def split = it.split(';')
    // remove "user:" prefix
    def email = split[0].split(':')[1]
    // remove "groups:" prefix
    def groups = split[1].split(':')[1]
    // create a map entry
    [(email), groups]
}


Then running map.forEach {k, v -> println "key: '${k}', value: '${v}'"} prints following: (standard map to string may be a little bit chaotic in this case)

key: '[email protected]', value: 'Team-1, Team-2'
key: '[email protected]', value: 'Team-2, Team-3'
key: '[email protected]', value: 'Team-1, Team-3'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VANAN