Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a list from another list transforming each element on Groovy

Tags:

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?

like image 319
Khelben Avatar asked Jan 22 '10 08:01

Khelben


People also ask

How do I merge two lists in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.

Which are the correct ways to define a List in Groovy?

In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.

How do you get the index of an element in a List in Groovy?

Groovy - indexOf() Returns the index within this String of the first occurrence of the specified substring. This method has 4 different variants. public int indexOf(int ch) − Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.


1 Answers

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)

like image 149
tim_yates Avatar answered Sep 23 '22 09:09

tim_yates