Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to code this, string to map conversion in Groovy

Tags:

string

map

groovy

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?

like image 555
Daxon Avatar asked May 11 '10 16:05

Daxon


People also ask

How do I convert a list to map in Groovy?

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.

How do I convert a string to a float in Groovy?

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.

How do I create a map object in Groovy?

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.

How do I convert a number to a string in Groovy?

toString() − This returns a String object representing the value of this Integer. toString(int i) − This returns a String object representing the specified integer.


2 Answers

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.

like image 128
ig0774 Avatar answered Sep 28 '22 08:09

ig0774


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]
}
like image 33
Dónal Avatar answered Sep 28 '22 10:09

Dónal