Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

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


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

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


Ranges allow you to create a list of sequential values. These can be used as Lists since

Error rendering macro 'link' : Link needs a name and a URL as arguments.
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.

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

Ranges can be used to iterate using the for statement.


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

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.

Note: by design 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()

Slicing with the subscript operator

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

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.

You can update items using the subscript operator too

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

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

  • No labels