Micor
Micor

Reputation: 1542

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. 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:

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]

Any ideas?

Upvotes: 19

Views: 53439

Answers (3)

Ford Guo
Ford Guo

Reputation: 971

In the latest grails, just use params.list('xxx').

Upvotes: 20

chrislatimer
chrislatimer

Reputation: 3560

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.

// 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

Upvotes: 5

Ted Naleid
Ted Naleid

Reputation: 26791

You can use flatten to get that:

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.

Upvotes: 29

Related Questions