编写这个的最佳方式,在Groovy中将字符串映射到地图转换 [英] Best way to code this, string to map conversion in Groovy

查看:105
本文介绍了编写这个的最佳方式,在Groovy中将字符串映射到地图转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,如

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

我想将其转换为地图

  [session,234567893egshdjchasd] 
[userId,12345673456]
[timeout,1800000]
/ pre>

这是我现在的方式,

  def map = [:] 

data.splitEachLine(&){

it.each {x - >

def object = x.split(=)
map.put(object [0],object [1])$ ​​b
$ b}

}

它有效,但是有更有效的方式吗?

解决方案

我不知道以为这会运行得更快,但它确实在语法简约方面表现出来:

  def data ='session = 234567893egshdjchasd& userId = 12345673456& timeOut = 1800000'
def result = data.split('&') .inject([:]){map,token - >
token.split('=')。与{map [it [0]] = it [1]}
map
}
/ pre>

个人而言,我喜欢Don的可读性和可维护性的答案,但根据上下文,这可能是适当的。



编辑:这实际上是重新格式化的一行。


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?

解决方案

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.

这篇关于编写这个的最佳方式,在Groovy中将字符串映射到地图转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆