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?
So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
Creating Groovy Listsutil. ArrayList. Note that cloning creates a shallow copy of the list. Groovy uses the “==” operator to compare the elements in two lists for equality.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With