Lists
Prerequisites: Ranges
A list is an ordered collection. [...] creates a
java.util.ArrayList.
def fruits = ['apple', 'banana', 'cherry']
println fruits[0]
println fruits[-1]
println fruits.size()
println fruits.first() + ' / ' + fruits.last()
println fruits.contains('banana')
println fruits.indexOf('cherry')
apple
cherry
3
apple / cherry
true
2
Indexes start at 0, and negative indexes count from the end.
Changing a list
def list = [3, 1, 2]
list << 4 // append (left-shift operator)
list.add(5)
list[0] = 30 // replace
list.remove(Integer.valueOf(2)) // remove by value
list.removeAt(0) // remove by index
println list
list.addAll([9, 8])
list.clear()
println list.isEmpty()
[1, 4, 5]
true
remove(2) on a list of integers removes the item at index 2 —
Java's overloading picks the index version. Use removeAt(i) for
indexes and remove(Integer.valueOf(x)) or removeElement(x) for
values, so the intent is clear.
Operators on lists
def a = [1, 2, 3]
println a + [4, 5] // new list
println a - [2] // remove all 2s
println a * 2 // repeat
println([[1, 2], [3, [4]]].flatten())
println([3, 1, 2].sort())
println([1, 2, 2, 3, 3].unique())
println([1, 2, 3].reverse())
println([5, 3, 9].max() + ' ' + [5, 3, 9].min() + ' ' + [5, 3, 9].sum())
[1, 2, 3, 4, 5]
[1, 3]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2, 3]
[3, 2, 1]
9 3 17
Notice the parentheses in println([3, 1, 2].sort()). Without them,
println [3, 1, 2] is read as println[3, 1, 2] — indexing a property called
println — and fails with a MissingPropertyException. When a method's first
argument starts with [, always use parentheses.
Mutating vs. non-mutating
def nums = [3, 1, 2]
def sorted = nums.sort(false) // false: return a sorted copy
println "nums=$nums sorted=$sorted"
nums.sort() // sorts in place!
println "nums=$nums"
def frozen = [1, 2].asImmutable()
try {
frozen << 3
} catch (UnsupportedOperationException e) {
println 'cannot change an immutable list'
}
nums=[3, 1, 2] sorted=[1, 2, 3]
nums=[1, 2, 3]
cannot change an immutable list
sort() and unique() change the original list (and return it).
Pass false to get a copy instead. asImmutable() wraps a list so
nobody can change it.
Practice
Start with [5, 3, 8, 1], append 7, remove the smallest number, and
print the list sorted from largest to smallest.
Show solution
def nums = [5, 3, 8, 1]
nums << 7
nums.removeElement(nums.min())
println nums.sort(false).reverse()
[8, 7, 5, 3]