Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Collections and Closures

Groovy Lists

Learn Groovy lists: literal syntax, indexing with negative numbers, slicing, adding and removing, sorting, uniqueness, flatten, spread, immutability and common mistakes.

Lists are the collection you will use most. Groovy gives them a literal syntax, operators for adding and removing elements, indexing that accepts negative numbers and ranges, and dozens of helper methods. Under the hood a Groovy list is a plain java.util.ArrayList (unless you ask for another type), so everything from Java's List also works.

Groovy blocks are read-only here, with runnable Java stand-ins where helpful.

Creating lists

GROOVY
def empty = []
def nums = [3, 1, 4, 1, 5]
def mixed = ['text', 42, 3.14, true, null]       // lists can hold anything
def nested = [[1, 2], [3, 4]]
def linked = [1, 2, 3] as LinkedList              // another list type
def fixed = new ArrayList<Integer>()

println nums.class                                // class java.util.ArrayList
println nums.size()                               // 5

[] is an empty list (and [:] an empty map, see Maps). Use generics in declarations when you want clarity: List<String> names = ['Ada', 'Bob']. Generics are not enforced at run time in a dynamic script.

Reading elements

GROOVY
def letters = ['a', 'b', 'c', 'd', 'e']
println letters[0]          // a
println letters[-1]         // e   (last)
println letters[-2]         // d
println letters[1..3]       // [b, c, d]  (a new list)
println letters[1, 3]       // [b, d]
println letters.first()     // a
println letters.last()      // e
println letters.head()      // a
println letters.tail()      // [b, c, d, e]
println letters[10]         // null (out of range returns null, no exception)

list[i] calls getAt(i). Unlike Java's get, an index past the end returns null rather than throwing, which can hide bugs, so check size() when it matters. Slices return new lists, not views.

Changing a list

GROOVY
def xs = [1, 2]
xs << 3                  // [1, 2, 3]   leftShift appends
xs.add(4)                // [1, 2, 3, 4]
xs += [5, 6]             // creates a NEW list [1..6] and rebinds xs
xs.addAll([7, 8])        // adds in place
xs[0] = 10               // replace
xs.remove(0)             // removes by index (returns the element)
xs.remove((Object) 7)    // removes by value in Java style
xs -= [8]                // creates a new list without 8
xs[20] = 1               // grows the list; the gap is filled with null

Two details trip up newcomers:

  • + and - create new lists; <<, add and addAll change the list in place. If another variable points to the same list, only the in-place methods affect it.
  • remove(int) takes an index. For a list of Integers use removeElement(5) or remove((Object) 5) to remove the value 5.

The Java stand-in shows the "new list versus in place" difference.

Java Java stand-in: in-place change versus a new list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Testing and searching

GROOVY
def xs = [5, 3, 8, 3]
println 3 in xs                  // true
println xs.contains(8)           // true
println xs.indexOf(3)            // 1
println xs.lastIndexOf(3)        // 3
println xs.count(3)              // 2
println xs.isEmpty()             // false
println xs.max()                 // 8
println xs.min()                 // 3
println xs.sum()                 // 19

sum() also works with a closure (people.sum { it.age }), and returns null for an empty list, so give a starting value: xs.sum(0).

Sorting and ordering

GROOVY
def xs = [5, 3, 8, 1]
println xs.sort()                       // [1, 3, 5, 8]   sorts IN PLACE and returns the list
println xs.sort(false)                  // returns a sorted copy, leaving xs alone
println xs.reverse()                    // [8, 5, 3, 1]
println ['pear', 'fig', 'apple'].sort { it.length() }     // [fig, pear, apple]
println ['pear', 'fig'].sort { a, b -> b <=> a }          // [pear, fig]

sort() mutates the list by default; pass false to keep the original. Sorting by a closure that returns a key is the neat Groovy replacement for writing a Comparator.

Unique, flatten, split and combine

GROOVY
println [1, 2, 2, 3, 3].unique()              // [1, 2, 3]
println [[1, 2], [3, [4]]].flatten()          // [1, 2, 3, 4]
println [1, 2, 3, 4, 5].take(2)               // [1, 2]
println [1, 2, 3, 4, 5].drop(2)               // [3, 4, 5]
println [1, 2, 3, 4].collate(2)               // [[1, 2], [3, 4]]
println ['a', 'b'].plus('c')                  // [a, b, c]
println(([1, 2, 3] + [3, 4]) - [3])          // [1, 2, 4]  (removes ALL 3s)
println [1, 2, 3].intersect([2, 3, 4])        // [2, 3]
println [1, 2, 3].disjoint([4, 5])            // true
println ['a', 'b', 'c'].join('-')             // a-b-c
println [[1, 'a'], [2, 'b']].transpose()      // [[1, 2], [a, b]]
println [1, 2, 3].withIndex()                 // [[1, 0], [2, 1], [3, 2]]

Note unique() also changes the list in place unless you pass false.

Iterating

GROOVY
def fruits = ['apple', 'kiwi']
fruits.each { println it }
fruits.eachWithIndex { f, i -> println "$i: $f" }
for (f in fruits) { println f }
fruits.reverseEach { println it }

For transformations (collect, findAll, inject) see Collection Methods in Depth and Closures.

Destructuring and spread

GROOVY
def (head, second) = ['x', 'y', 'z']     // head=x, second=y
def args = [1, 2, 3]
println Math.max(*args)                  // 3
println [0, *args, 4]                    // [0, 1, 2, 3, 4]

Immutable and typed lists

GROOVY
def readOnly = [1, 2, 3].asImmutable()
// readOnly << 4                         // throws UnsupportedOperationException
def fixed = List.of('a', 'b')            // Java 9+ immutable list

An array is different from a list: int[] arr = [1, 2, 3] and def arr = [1, 2, 3] as int[] create a Java array with a fixed size. Arrays support [] and most list methods too.

Common mistakes

  • Expecting list[10] to throw. It returns null.
  • Using remove(5) on List<Integer> and removing the element at index 5 instead of the value 5.
  • Forgetting that sort() and unique() modify the receiver.
  • Mixing a list and an array: == between them is false.
Java Java stand-in: Groovy-style slices and negative indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ['a', 'b', 'c'][-1] return?

    Negative indexes count from the end of the list, so -1 is the last element.
  2. 2. What is the difference between xs << 4 and xs + [4]?

    leftShift appends to the existing list. plus returns a new list and leaves the original unchanged.
  3. 3. What does [1, 2, 3][10] evaluate to?

    Groovy's list indexing returns null for out-of-range reads, unlike Java's get.
  4. 4. Which call sorts a list WITHOUT changing the original?

    sort(false) returns a sorted copy. The default sort() is mutating.

Summary

  • Lists are ArrayLists with literal syntax [ ], negative and range indexes, and null for out-of-range reads.
  • <<, add, addAll mutate; + and - return new lists.
  • sort() and unique() mutate by default; pass false for a copy.
  • flatten, take, drop, collate, intersect, join and spread cover most day-to-day needs.
  • Use asImmutable() for read-only views.

Next: Maps