Closures
Closures, another powerful Groovy feature, represent syntactical shorthands that can save you a few lines of code. You can read about them in detail in the official Groovy documentation.
Sorting
You can utilize the method sort
 on a collection or a map, passing the comparator in the form of a Closure.
def competitors = api.productExtension('Competition') // a and b are named parameters and represent the arguments the Closure is called with. In this case it's the two elements being compared. // you can rename a and b to whatever you want def sortedByName = competitors.sort { a, b -> // assuming attribute2 is a number, we need to convert it to BigDecimal in order to compare it correctly (as a number, not as a string) return a.attribute2?.toBigDecimal() <=> b.attribute2?.toBigDecimal() }
Iterating
Iterating through a collection or a map is far better when done with Closures.Â
def competitors = api.productExtension('Competition') Â competitors.each { c -> api.trace('Competitor name', '', c.attribute1)} Â // in case we don't name the closure parameter, we can reference it with variable called 'it' competitors.each { api.trace('Competitor name', '', it.attribute1} Â // iterating with an index competitors.eachWithIndex { comp, i -> api.trace('Competitor ${i}', '', comp.attribute1) } Â // you can also iterate through a map using an Entry map.each { api.trace(it.key, '', it.value) } Â // or using key and value map.each { key, value -> api.trace(key, '', value) }
Filtering Collection
Create map from a collection
def competitors = api.productExtension('Competition') // get competitors whose price (attribute2) is greater than 100 def filtered = competitors.findAll{ it.attribute2?.toBigDecimal() > 100 }
Transforming Collection
Transforming one collection of records into another on one line:
Create map from a collection
def competitors = api.productExtension('Competition') // convert to a collection of competitors' names def names = competitors.collect{ it.attribute1 }
Creating Map from Collection
Closures allow you to create a map out of a collection on one line:
Create map from a collection
def competitors = api.productExtension('Competition') // return an object with the attribute1 as key and attribute2 as value // notice the parentheses around the key competitors.collectEntries{ [(it.attribute1) : it.attribute2] }
Strong Typing
Sometimes it is useful to create an object of a certain Class and not to rely on Groovy. You can do it like this:
// the list will be a HashSet def list = [] as HashSet  // the map will be a TreeMap def map = [:] as TreeMap
Found an issue in documentation? Write to us.
Â