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 3 Next »

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

h2 Lists

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

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

h2 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.

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.

h2 Maps

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.

h2 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