Skip to content

Collections

Philip Ford edited this page Aug 27, 2017 · 12 revisions

Lists

[item1, item2, ...]
  • The list items are separated by commas within brackets.
  • To create an empty list, assign empty brackets to a reference.
  • Use the << leftShift operator to append elements to a list.

Maps

[key1: value1, key2: value2, ...]
  • Syntax: a comma-separate list of key/value pairs in brackets.
  • Each key is separated from its value by a colon.
  • To create an empty map, assign brackets containing only a colon, [:], to a reference.
  • There are at least 5 ways to add an item to a map, including bracket notation (e.g., map['item1'] = 'Hi!'), shown below.

Bracket Notation

You can add values to or retrieve values from a Groovy map with bracket notation, just like JavaScript objects:

// Here is an example map declaration with initial values 
def personAgeMap = [matthew: 30, mark:25, luke: 40]

// Since Groovy is just a superset of Java, we can use the put method to add an entry to a map. 
personAgeMap.put('john', 41)

// We can also use bracket notation. For example: 
personAgeMap['Tim'] = 28

// Another way is to treat the key as property of the map object. Example: 
personAgeMap.Roy = 32

// You can also use dot (.) followed by the key enclosed in quotes. Example: 
personAgeMap.'Tim' = 55

// Lastly, you can add entries coming from another map. You can push entries from one map to another, for example:
personAgeMap << [Michael:29]

Arrays

Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitly define the type of the array through coercion or type declaration.

//Define an array of strings using explicit variable type declaration
String[] arrStr = ['Ananas', 'Banana', 'Kiwi']  

assert arrStr instanceof String[]    
assert !(arrStr instanceof List)

// Alternatively, create an array of ints with the as operator
def numArr = [1, 2, 3] as int[]      

assert numArr instanceof int[]       
assert numArr.size() == 3

// You can also create multi-dimensional arrays:
def matrix3 = new Integer[3][3]  // You can define the bounds of a new array     
assert matrix3.size() == 3

Integer[][] matrix2     // Or declare an array without specifying its bounds                
matrix2 = [[1, 2], [3, 4]]
assert matrix2 instanceof Integer[][]
  • Access to elements of an array follows the same notation as for lists:

    String[] names = ['Cédric', 'Guillaume', 'Jochen', 'Paul']
    assert names[0] == 'Cédric'    // Retrieve the first element of the array
    
    names[2] = 'Blackdrag'    // Set the value of the third element of the array to a new value      
    assert names[2] == 'Blackdrag'
  • Java’s array initializer notation is not supported by Groovy: the curly braces can be misinterpreted with the notation of Groovy closures.

References

Clone this wiki locally