Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String or String[] to List with Groovy

Tags:

grails

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?

like image 758
Micor Avatar asked Jul 01 '10 22:07

Micor


People also ask

Can we convert String [] to String?

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.

What does [] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I create a List in Groovy?

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.


1 Answers

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.

like image 127
Ted Naleid Avatar answered Oct 09 '22 16:10

Ted Naleid