1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-08-06 14:56:54 +02:00

Merge pull request #294 from timyates/master

A few Groovy improvements
This commit is contained in:
Adam Bard
2013-09-02 21:31:43 -07:00

View File

@@ -8,7 +8,7 @@ filename: learngroovy.groovy
Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org) Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org)
```cpp ```groovy
/* /*
Set yourself up: Set yourself up:
@@ -51,28 +51,56 @@ println x
/* /*
Collections and maps Collections and maps
*/ */
//Creating an empty list //Creating an empty list
def technologies = [] def technologies = []
//Add an element to the list /*** Adding a elements to the list ***/
technologies << "Groovy"
// As with Java
technologies.add("Grails") technologies.add("Grails")
// Left shift adds, and returns the list
technologies << "Groovy"
// Add multiple elements
technologies.addAll(["Gradle","Griffon"]) technologies.addAll(["Gradle","Griffon"])
//Remove an element from the list /*** Removing elements from the list ***/
// As with Java
technologies.remove("Griffon") technologies.remove("Griffon")
//Iterate over elements of a list // Subtraction works also
technologies = technologies - 'Grails'
/*** Iterating Lists ***/
// Iterate over elements of a list
technologies.each { println "Technology: $it"} technologies.each { println "Technology: $it"}
technologies.eachWithIndex { it, i -> println "$i: $it"} technologies.eachWithIndex { it, i -> println "$i: $it"}
/*** Checking List contents ***/
//Evaluate if a list contains element(s) (boolean) //Evaluate if a list contains element(s) (boolean)
technologies.contains('Groovy') contained = technologies.contains( 'Groovy' )
// Or
contained = 'Groovy' in technologies
// Check for multiple contents
technologies.containsAll(['Groovy','Grails']) technologies.containsAll(['Groovy','Grails'])
//Sort a list /*** Sorting Lists ***/
// Sort a list (mutates original list)
technologies.sort() technologies.sort()
// To sort without mutating original, you can do:
sortedTechnologies = technologies.sort( false )
/*** Manipulating Lists ***/
//Replace all elements in the list //Replace all elements in the list
Collections.replaceAll(technologies, 'Gradle', 'gradle') Collections.replaceAll(technologies, 'Gradle', 'gradle')