30

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 3

38

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)

3
  • 1
    Unfortunately, this operator doesn't work in Jenkins Pipeline groovy script
    – smoke_lp
    Jun 24, 2020 at 10:13
  • 3
    @smoke_lp How about lines = rawLines.collect { it.name }
    – tim_yates
    Jun 24, 2020 at 10:39
  • @tim_yates I think Jenkins doesn't allow collect either. Aug 3, 2022 at 7:17
26

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)}
0

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.

1
  • Yes, this is one of these cases ;-) The table is a view, so there are some problems defining the table as a domain.
    – Khelben
    Jan 22, 2010 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.