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

后端 未结 8 2014
情深已故
情深已故 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:03

    Here's my effort, which initializes and fills the map in one go, and avoids the inject method which I personally find hard to follow:-

        def map = data.split('&').collectEntries {
            def kvp = it.split('=').collect { string ->
                string = string.trim()
                return string
        }
        [(kvp[0]): kvp.size() > 1 ? kvp[1] ?: '' : '']
        // the null check is almost certainly overkill so you could use :-
        // [(kvp[0]): kvp.size() > 1 ? kvp[1] : '']
        // this just checks that a value was found and inserts an empty string instead of null 
    }
    

提交回复
热议问题