简体   繁体   English

使用Groovy将String或String []转换为List

[英]Convert String or String[] to List with Groovy

I have a multiple select variable posting to controller. 我有一个多选择变量发布到控制器。 The way multiple select works is that it is passed as a single String if there was only one value selected and as a String[] if more than one values selected. 多个选择的工作方式是,如果只选择了一个值,则将其作为单个String传递;如果选择了多个值,则将其作为String []传递。 I want to keep processing simple and treat the passed value(s) the same. 我想保持处理简单并将传递的值视为相同。 So the best way I can up with is to convert it to List like so: 所以我能做到的最好的方法是将其转换为List,如下所示:

def selectedValues = params.selectedValues

List valuelist = new ArrayList()

if(selectedValues instanceof String) {
    valuelist.add(selectedValues)
} else {
    valuelist = selectedValues as List
}

It works but I am curious if there is a groovier way to do this, maybe with a one liner :). 它有效,但我很好奇,如果有一个更通常的方式来做这个,也许有一个班轮:)。

Of course if I simply do: 当然,如果我只是这样做:

List valuelist = selectedValues as List

It will not work for a single selected value as it will convert it from lets say 24 to [2,4] 它不适用于单个选定值,因为它会将它从24个转换为[2,4]

Any ideas? 有任何想法吗?

You can use flatten to get that: 您可以使用flatten来实现:

def toList(value) {
    [value].flatten().findAll { it != null }
}

assert( ["foo"] == toList("foo") )
assert( ["foo", "bar"] == toList(["foo", "bar"]) )
assert( [] == toList([]) )
assert( [] == toList(null) )

Or, if you don't want a separate method, you can do it as a one liner: 或者,如果您不想使用单独的方法,则可以将其作为一个单独的方法:

[params.selectedValues].flatten().findAll{ it != null }

I'd personally just write two methods and let the type system deal with it for me: 我个人只是写了两个方法,让类型系统为我处理它:

def toList(String value) {
    return [value]
}

def toList(value) {
    value ?: []
}

assert( ["foo"] == toList("foo") )
assert( ["foo", "bar"] == toList(["foo", "bar"]) )
assert( [] == toList([]) )
assert( [] == toList(null) )

It's more efficient and I think a little more obvious what's going on. 它效率更高,我认为发生了什么更明显。

在最新的grails中,只需使用params.list('xxx')

try this: 试试这个:

def valueList = []
valueList = valueList + params?.selectedValues

Update: A couple other options depending on what you want the null case to be. 更新:其他几个选项取决于您想要的空案例。 As Ted pointed out, the above solution will return [null] when params?.selectedValues is null, which may not be what you want. 正如Ted所指出的,当params?.selectedValues为null时,上面的解决方案将返回[null],这可能不是你想要的。

// if you want null to return []
def valueList = [] + (params?.selectedValues ?: [])

or 要么

// if you want null to return null
def valueList = params?.selectedValues ? ([] + params?.selectedValues) : null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM