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

后端 未结 8 2032
情深已故
情深已故 2020-12-31 07:22

I have a string like

def data = \"session=234567893egshdjchasd&userId=12345673456&timeOut=1800000\"

I want to convert it to a map

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 08:11

    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.

提交回复
热议问题