views:

300

answers:

3

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?

+2  A: 

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]
}
Don
+3  A: 

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 -> 
    token.split('=').with { map[it[0]] = it[1] }
    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.

ig0774
+1 for use of fancy GDK methods (inject) and fancy English phrases (syntactic parsimony)
Don
you can change the inject innards to token.split('=').with { map << [ (it[0]):it[1] ] } if you _really_ hate readability ;-)
tim_yates
A: 

If you're looking for efficient, regular expressions are where it's at:

def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
def map = [:]
data.findAll(/([^&=]+)=([^&]+)/) { full, name, value ->  map[name] = value }

println map

prints:

[session:234567893egshdjchasd, userId:12345673456, timeOut:1800000]

If you're not familiar with regular expressions, it might look a little foreign, but it's really not that complicate. It just has two (groups), the first group is any character but a "&" or a "=". The second group is any character besides a "=". The capture groups are on either side of a "=".

Ted Naleid