Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Groovy has native language support for collections, lists, maps and arrays.

Lists

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

Each list expression creates an implementation of java.util.List.

See Lists and Sets for more information on using Lists.

Ranges

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 exclusive, 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 an exclusive 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

Note that ranges are implemented efficiently, creating a lightweight Java object containing a from and to value.

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;
}

Maps
Anchor
maps
maps

Maps can be created using the following syntax. Notice that [:] is the empty map expression.

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

Note: by design map.foo will always look for the key foo in map. This means foo.class will return null on an empty map and not result in calling the method getClass()

See Maps for more information on using maps.

Getting efficient with the star-dot '*.' operator

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()

Enhanced Collection Methods

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']

In addition to findAll and collect shown above, you have methods like findIndexOf, grep, any, every, min, max, flatten, intersect, disjoint, sort, join and others. Simply look up the GDK doco for more details. You might want to look up the added methods for Collection, List and Object to start with.

Some more details about these methods can also be found in the Quick Start Guide under JN1015-Collections.

Slicing with the subscript operator

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"

Dynamic objects (Expandos)

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()

The player.greeting assignment passes in a closure to execute when greeting() is called on the Expando. Notice that the closure has access to the properties assigned to the Expando, even though these values may change over time, using Groovy's GString "$variableOrProperty" notation.