Khelben
Khelben

Reputation: 6461

Generate a list from another list transforming each element on Groovy

I've got the following code on a Controller

    def db = new Sql(dataSource)
    def rawLines = db.rows("SELECT name FROM LINES")
    def lines = []
    /*(db.rows returns the values as [NAME:value] */
    rawLines.each {
        lines.add(it.name)
    }
    /*Then, use lines */

I can't keep away the impression that there is probably some way to do this in a more elegant way, something similar to a list comprehension in Python:

lines = [ l.name for l in db.rows("SELECT name FROM LINES") ]

Having to declare an empty list and then populate it doesn't seem the best way of doing things... Is it possible to do something like this, or Groovy doesn't allow it?

Upvotes: 31

Views: 27945

Answers (3)

Meysam
Meysam

Reputation: 609

tim_yates' answer is a clean solution when you want to call a method (or property) on each element of list in order to transform it e.g.:

[1,2,3]*.multiply(5)

but if you want to call a method from another object or do something more complex you can use collect:

[1, 2, 3].collect {Math.cos(it * Math.PI)}

Upvotes: 27

tim_yates
tim_yates

Reputation: 171084

Can't you just use the spread operator, and do:

lines = rawLines*.name

(see http://docs.groovy-lang.org/latest/html/documentation/index.html#_spread_operator)

Upvotes: 38

gizmo
gizmo

Reputation: 11909

Well, If you are using grails, why aren't you simply using the a model class together with the findAll method?
Using plain raw SQL should be done on exceptional cases.

Upvotes: 0

Related Questions