/*
Collections and maps
*/
//Creating an empty list
def technologies = []
/*** Adding a elements to the list ***/
// As with Java
technologies.add("Grails")
// Left shift adds, and returns the list
technologies << "Groovy"
// Add multiple elements
technologies.addAll(["Gradle","Griffon"])
/*** Removing elements from the list ***/
// As with Java
technologies.remove("Griffon")
// Subtraction works also
technologies = technologies - 'Grails'
/*** Iterating Lists ***/
// Iterate over elements of a list
technologies.each { println "Technology: $it"}
technologies.eachWithIndex { it, i -> println "$i: $it"}
/*** Checking List contents ***/
//Evaluate if a list contains element(s) (boolean)
contained = technologies.contains( 'Groovy' )
// Or
contained = 'Groovy' in technologies
// Check for multiple contents
technologies.containsAll(['Groovy','Grails'])
/*** Sorting Lists ***/
// Sort a list (mutates original list)
technologies.sort()
// To sort without mutating original, you can do:
sortedTechnologies = technologies.sort( false )
/*** Manipulating Lists ***/
//Replace all elements in the list
Collections.replaceAll(technologies, 'Gradle', 'gradle')
//Shuffle a list
Collections.shuffle(technologies, new Random())
//Clear a list
technologies.clear()
[11, 12, 13, 14] – A list of integer values
[‘Angular’, ‘Groovy’, ‘Java’] – A list of Strings
[1, 2, [3, 4], 5] – A nested list
[‘Groovy’, 21, 2.11] – A heterogeneous list of object references
[ ] – An empty list
No comments:
Post a Comment