Collections

There are a number of collections in Groovy, ranges which is not in Java allows you to create a list of sequential values, lists and maps which are similar to the Java versions.

Ranges

Ranges allow you to create a list of sequential values using two dot notations

Range examples
Range r = 1..10
println "Range: " + r
println "Range: ${r}"
println r.class.name
println r.from                              // starting position in this case 1
println r.to                                // ending position in this case 10

Range r2 = 1..<10                           // Won't include the 10
println "Range: ${r2}"                      // Notice the 10 is missing

Range r3 = 10..1                            // You can also reverse the numbers
println "Range: ${r3}"
println "--------------"

assert (0..10).contains(0)
assert (0..10).contains(5)
assert (0..10).contains(10)
assert (0..10).contains(-1) == false
assert (0..10).contains(11) == false

assert (0..<10).contains(0)
assert (0..<10).contains(10) == false

Date today = new Date()
Date oneWeekAway = today + 7 // thank the GDK for that simple statement

println today
println oneWeekAway

Range days = today..oneWeekAway
println days

Range letters = 'a'..'z'
println letters
Practical example of ranges
enum Days {
    SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
}

def dayRange = Days.SUNDAY..Days.SATURDAY

dayRange.each { day ->
    println day
}

println dayRange.size()
println dayRange.contains(Days.WEDNESDAY)

// Bonus: next() and previous() are equivalent to ++ and -- operators.
def wednesday = Days.WEDNESDAY
assert Days.THURSDAY == ++wednesday
assert Days.WEDNESDAY == --wednesday

Lists

The List is a structure used to store a collection of data items. 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, starting at 0. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.

Lists have many methods that you can use like push(), pull(), pop(), remove() and many many more.

List examples
List nums = [1,2,3,6,7,9,4,5,3,6,8,9]
println nums
println nums.class.name

List nums2 = [1,2,3,6,7,9,4,5,3,6,8,9] as LinkedList
println nums2.class.name

// add to List
nums.push(99)
nums.putAt(0,77)        // should use below, it's the same
nums[0] = 78
nums + 7                // this does not change original List (creates new list which you need to assign)
nums << 66
println nums

// remove from List
nums.pop()
nums.removeAt(0)
def newList = nums - 3                           // minus like plus does not change original List
println newList

// get from List
println "getAt: " + nums.getAt(0..3)             // retrieve elements 0-3 from the list

// clear the list
nums = []

// flatten
nums << [3,4,5]
nums << [1,2]
println nums                                     // list contains list of lists
println nums.flatten()                           // flatten all lists into one big list
 
// equals
def myNumbers = [1,2,3]
def myNumbers2 = [1,2,3]
println myNumbers.equals(myNumbers2)

// findAll
println nums.findAll { it == 4 }
println nums.flatten().findAll { it < 4 }

// getAt(Range)
println "Current List: ${nums}"
println nums.getAt(1)

// reverse list
println nums.reverse()

// unique
println nums.unique()

// Java Collections List(LinkedList) (Set,SortedSet)
def evens = [10,2,8,4,24,14,2] as Set
println evens
println evens.class.name

Maps

A Map is an unordered collection of object references. The elements in a Map collection are accessed by a key which points to its value (key/value pair). The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value.

Maps have many methods that you can use like size(), sort(), clear() get() and many many more.

Map examples
def map = [:]                           // Using a colon means a Map
println map                             // LinkedHashMap
println map.getClass().getName()        // can use class.name

def person = [first:"Paul", last:"Valle", email:"paul.valle@example.com"]         // Notice key/value pairs
println person
println person.first                    // accessing first key
println person["email"]                 // accessing using the key

person.twitter = "@paulvalle"           // adding new field called twitter
println person

def emailKey = "EmailAddress"
def twitter = [username:"@paulvalle",(emailKey):"paul.valle@example.com"]          // you can use a variable for the key name

println person.size()                                                              // there are many methods that you can use
println person.sort()

// looping through person
println "-----------------------------------------------------"
for( entry in person ) {
    println entry
}

println "-----------------------------------------------------"
for( key in person.keySet() ) {
    println "$key:${person[key]}"
}