对此进行编码的最佳方式,Groovy 中字符串到映射的转换 [英] Best way to code this, string to map conversion in Groovy
本文介绍了对此进行编码的最佳方式,Groovy 中字符串到映射的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的字符串
def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
我想把它转换成地图
["session", 234567893egshdjchasd]
["userId", 12345673456]
["timeout", 1800000]
这是我目前的做法,
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?
推荐答案
我不知道这是否会运行得更快,但它确实在语法简洁方面表明了自己:
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
}
就个人而言,我喜欢 Don 在可读性和可维护性方面的回答,但根据上下文,这可能是合适的.
Personally, I like Don's answer for readability and maintainability, but depending on context, this may be appropriate.
这实际上是重新格式化的单行.
This is actually a reformatted one-liner.
这篇关于对此进行编码的最佳方式,Groovy 中字符串到映射的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文