I have a string like
def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
I want to convert it to a map
["session", 234567893egshdjchasd]
["userId", 12345673456]
["timeout", 1800000]
This is the current way I am doing it,
def map = [:]
data.splitEachLine("&"){
it.each{ x ->
def object = x.split("=")
map.put(object[0], object[1])
}
}
It works, but is there a more efficient way?
Using a SpreadMap we will convert a list of strings into a map. A SpreadMap is a helper that turns a list with an even number of elements into a Map. In the snippet below, we create a map keyed by NFL city while the value will be the team name.
This example will show how to convert a string to a double or float in groovy. Calling the string replace we will move all the special charachters. Next calling the parseFloat() or parseDouble() we will transform the string to a number.
2. Creating Groovy Maps. We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line.
toString() − This returns a String object representing the value of this Integer. toString(int i) − This returns a String object representing the specified integer.
I don't know think this is would run any faster, but it does suggest itself in terms of syntactic parsimony:
def data = 'session=234567893egshdjchasd&userId=12345673456&timeOut=1800000'
def result = data.split('&').inject([:]) { map, token ->
//Split at "=" and return map with trimmed values
token.split('=').with {
map[it[0].trim()] = it[1].trim()
}
map
}
Personally, I like Don's answer for readability and maintainability, but depending on context, this may be appropriate.
Edit: This is actually a reformatted one-liner.
I don't know if this is more efficient, but to my eyes, it's a bit simpler (YMMV)
def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
def map = [:]
data.split("&").each {param ->
def nameAndValue = param.split("=")
map[nameAndValue[0]] = nameAndValue[1]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With