Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed 'exclusive' to 'half-open' when referring to ranges which exclude their last value.

...

You can create lists as follows. Notice that [] is the empty list expression.

Code Block

def list = [5, 6, 7, 8]
assert list.get(2) == 7
assert list[2] == 7
assert list instanceof java.util.List

def emptyList = []
assert emptyList.size() == 0
emptyList.add(5)
assert emptyList.size() == 1

...

Ranges allow you to create a list of sequential values. These can be used as Lists since Range extends java.util.List.
Ranges defined with the .. notation are inclusive (that is the list contains the from and to value).
Ranges defined with the ..< notation are exclusivehalf-open, they include the first value but not the last value.

Code Block

// an inclusive range
def range = 5..8
assert range.size() == 4
assert range.get(2) == 7
assert range[2] == 7
assert range instanceof java.util.List
assert range.contains(5)
assert range.contains(8)

// lets use ana exclusivehalf-open range
range = 5..<8
assert range.size() == 3
assert range.get(2) == 7
assert range[2] == 7
assert range instanceof java.util.List
assert range.contains(5)
assert ! range.contains(8)

//get the end points of the range without using indexes
def range = 1..10
assert range.from == 1
assert range.to == 10

...

Ranges can be used for any Java object which implements java.lang.Comparable for comparison and also have methods next() and previous() to return the next / previous item in the range.
e.g. you can use Strings in a range

Code Block

// an inclusive range
def range = 'a'..'d'
assert range.size() == 4
assert range.get(2) == 'c'
assert range[2] == 'c'
assert range instanceof java.util.List
assert range.contains('a')
assert range.contains('d')
assert ! range.contains('e')

Ranges can be used to iterate using the for statement.

Code Block

for (i in 1..10) {
  println "Hello ${i}"
}

but alternatively you can achieve the same effect, by iterating a range with each method:

Code Block

(1..10).each { i ->
  println "Hello ${i}"
}

Ranges can be also used in the switch statements:

Code Block

switch (years) {
   case 1..10: interestRate = 0.076; break;
  case 11..25: interestRate = 0.052; break;
      default: interestRate = 0.037;
}

...

Map keys are strings by default: [a:1] is equivalent to ["a":1]. But if you really want a variable to become the key, you have to wrap it between parentheses: [(a):1].

Code Block

def map = [name:"Gromit", likes:"cheese", id:1234]
assert map.get("name") == "Gromit"
assert map.get("id") == 1234
assert map["name"] == "Gromit"
assert map['id'] == 1234
assert map instanceof java.util.Map

def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.put("foo", 5)
assert emptyMap.size() == 1
assert emptyMap.get("foo") == 5

Maps also act like beans so you can use the property notation to get/set items inside the Map provided that the keys are Strings which are valid Groovy identifiers.

Code Block

def map = [name:"Gromit", likes:"cheese", id:1234]
assert map.name == "Gromit"
assert map.id == 1234

def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.foo = 5
assert emptyMap.size() == 1
assert emptyMap.foo == 5

...

You can perform operations on all the members of a collection using the '*.' operator, e.g.:

Code Block

assert [1, 3, 5] == ['a', 'few', 'words']*.size()

...

In addition to providing the literal syntax for collections, Groovy adds some additional methods to make working with collections more convenient. As an example, you can find big words from a list as follows:

Code Block

def words = ['ant', 'buffalo', 'cat', 'dinosaur']
assert words.findAll{ w -> w.size() > 4 } == ['buffalo', 'dinosaur']

Or you can find the first letters of some words as follows:

Code Block

def words = ['ant', 'buffalo', 'cat', 'dinosaur']
assert words.collect{ it[0] } == ['a', 'b', 'c', 'd']

...

You can index into Strings, Lists, arrays, Maps, regexs and such like using the subscript expression.

Code Block

def text = "nice cheese gromit!"
def x = text[2]

assert x == "c"
assert x.class == String

def sub = text[5..10]
assert sub == 'cheese'

def map = [name:"Gromit", likes:"cheese", id:1234]

assert map["name"] == "Gromit"
assert map.name == "Gromit"

def list = [10, 11, 12]
def answer = list[2]
assert answer == 12

Notice that you can use ranges to extract part of a List/array/String/regex. This is often referred to as slicing in scripting languages like Python. You can also use a list of indexes too.

Code Block

def list = 100..200
def sub = list[1, 3, 20..25, 33]
assert sub == [101, 103, 120, 121, 122, 123, 124, 125, 133]

You can update items using the subscript operator too

Code Block

def list = ["a", "b", "c"]
list[2] = "d"
list[0] = list[1]
list[3] = 5
assert list == ["b", "b", "d", 5]

You can use negative indices to count from the end of the List, array, String etc.

Code Block

def text = "nice cheese gromit!"
def x = text[-1]
assert x == "!"

def name = text[-7..-2]
assert name == "gromit"

Also if you use a backwards range (the starting index is greater than the end index) then the answer is reversed.

Code Block

def text = "nice cheese gromit!"
def name = text[3..1]
assert name == "eci"

...

The Expando is not a collection in the strictest sense, but in some ways it is similar to a Map, or objects in JavaScript that do not have to have their properties defined in advance. It allows you to create dynamic objects by making use of Groovy's closure mechanisms. An Expando is different from a map in that you can provide synthetic methods that you can call on the object.

Code Block

def player = new Expando()
player.name = "Dierk"
player.greeting = { "Hello, my name is $name" }

println player.greeting()
player.name = "Jochen"
println player.greeting()

...