Slashlinux
Slashlinux

Reputation: 161

load the data list from the file into a map in groovy split by colon

I have a below list and I want to load the data into a map in Groovy using split method to separate the key-value pairs and then iterate them to populate the map.

myfile.txt

name:john
name2:peter
name3:albert

expected result:

[name: 'john', name2: 'peter', name3: 'albert']

My code is - "map_users.groovy":

  def readFile = sh(returnStdout: true, script: "cat myfile.txt").trim()
     def map = [:]
        readFile.eachLine {line ->
           def(key,value) = line.split(':')
               map[key.trim()] : value.toString()
                   }
            println map

Upvotes: 1

Views: 159

Answers (1)

Andrej Istomin
Andrej Istomin

Reputation: 3033

You should use = when assigning the value to the map. So, instead of map[key.trim()] : value.toString() it should be: map[key.trim()] = value.toString(). Here is the working code:

def map = [:]
readFile.eachLine { line ->
    def (key, value) = line.split(':')
    map[key.trim()] = value.toString()
}
println map

If your file is not too big, you may also consider to use collectEntries to transform lines into map:

def map = readFile.readLines().collectEntries {line ->
    def (key, value) = line.split(':')
    [(key.trim()) : value.toString()]
}
println map

Upvotes: 0

Related Questions