Generate a list from another list transforming each element on Groovy

Viewed 20883

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?

3 Answers

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.

Related