Lists

A list literal is square brackets, and the object behind it is a java.util.ArrayList. Everything a Java list does works, and the GDK adds indexes from the end, slices and operators.

A list and its indexes

lists.groovy

def letters = ['b', 'a', 'c'] letters << 'd' letters.add(0, 'z') println letters println letters[0] println letters[-1] println letters[1..2] println letters.size() println letters.contains('a') println letters.indexOf('c')

groovy lists.groovy

[z, b, a, c, d]
z
d
[b, a]
5
true
3

<< appends and returns the same list, so two of them can be chained. A negative index counts from the end: -1 is the last element. A range as an index is a slice, and the result is a new list.

Adding, removing and sorting

change.groovy

def numbers = [3, 1, 2] numbers.add(4) numbers.remove(0) numbers.remove(Integer.valueOf(2)) println numbers println numbers + [5, 6] println numbers - [1] println numbers.sort() println numbers.reverse()

groovy change.groovy

[1, 2]
[1, 2, 5, 6]
[2]
[1, 2]
[2, 1]

remove(0) removes by index, and remove(Integer.valueOf(2)) removes the value 2, which is the ambiguity every Java list has. + and - return a new list; sort() and reverse() change the list they are called on and return it for chaining.

Nested lists and flatten

nested.groovy

def grid = [[1, 2], [3, 4], [5]] println grid println grid.size() println grid*.size() println grid.flatten() println grid.sum { List<Integer> row -> row.sum() }

groovy nested.groovy

[[1, 2], [3, 4], [5]]
3
[2, 2, 1]
[1, 2, 3, 4, 5]
15

flatten() makes one list of every element, at any depth, and sum with a closure adds the value the closure returns for each row. Together they replace two nested loops.

Related

Автор статьи: Arthur Isaev