Reputation: 161
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
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