def list = [5, 6, 7, 8] assert list.size() == 4 assert list.getClass() == ArrayList // the specific kind of list being used
assert list[2] == 7// indexing starts at 0 assert list.getAt(2) == 7// equivalent method to subscript operator [] assert list.get(2) == 7// alternative method
list[2] = 9 assert list == [5, 6, 9, 8,] // trailing comma OK
list.putAt(2, 10) // equivalent method to [] when value being changed assert list == [5, 6, 10, 8] assert list.set(2, 11) == 10// alternative method that returns old value assert list == [5, 6, 11, 8]
assert ['a', 1, 'a', 'a', 2.5, 2.5f, 2.5d, 'hello', 7g, null, 9asbyte] //objects can be of different types; duplicates allowed
assert [1, 2, 3, 4, 5][-1] == 5// use negative indices to count from the end assert [1, 2, 3, 4, 5][-2] == 4 assert [1, 2, 3, 4, 5].getAt(-2) == 4// getAt() available with negative index... try { [1, 2, 3, 4, 5].get(-2) // but negative index not allowed with get() assertfalse } catch (e) { assert e instanceof ArrayIndexOutOfBoundsException }
List as a boolean expression
list还可以计算出boolean表达式.
1 2 3 4
assert ![] // an empty list evaluates as false
//all other lists, irrespective of contents, evaluate as true assert [1] && ['a'] && [0] && [0.0] && [false] && [null]
Iterating on a list
可以通过each, eachWithIndex遍历整个集合.
1 2 3 4 5 6
[1, 2, 3].each { println "Item: $it"// `it` is an implicit parameter corresponding to the current element } ['a', 'b', 'c'].eachWithIndex { it, i -> // `it` is the current element, while `i` is the index println "$i: $it" }
def list = [0] // it is possible to give `collect` the list which collects the elements assert [1, 2, 3].collect(list) { it * 2 } == [0, 2, 4, 6] assert list == [0, 2, 4, 6]
assert [1, 2, 3].find { it > 1 } == 2// find 1st element matching criteria assert [1, 2, 3].findAll { it > 1 } == [2, 3] // find all elements matching critieria assert ['a', 'b', 'c', 'd', 'e'].findIndexOf { // find index of 1st element matching criteria it in ['c', 'e', 'g'] } == 2
assert ['a', 'b', 'c', 'd', 'c'].indexOf('c') == 2// index returned assert ['a', 'b', 'c', 'd', 'c'].indexOf('z') == -1// index -1 means value not in list assert ['a', 'b', 'c', 'd', 'c'].lastIndexOf('c') == 4
assert [1, 2, 3].every { it < 5 } // returns true if all elements match the predicate assert ![1, 2, 3].every { it < 3 } assert [1, 2, 3].any { it > 2 } // returns true if any element matches the predicate assert ![1, 2, 3].any { it > 3 }
assert [1, 2, 3, 4, 5, 6].sum() == 21// sum anything with a plus() method assert ['a', 'b', 'c', 'd', 'e'].sum { it == 'a' ? 1 : it == 'b' ? 2 : it == 'c' ? 3 : it == 'd' ? 4 : it == 'e' ? 5 : 0 // custom value to use in sum } == 15 assert ['a', 'b', 'c', 'd', 'e'].sum { ((char) it) - ((char) 'a') } == 10 assert ['a', 'b', 'c', 'd', 'e'].sum() == 'abcde' assert [['a', 'b'], ['c', 'd']].sum() == ['a', 'b', 'c', 'd']
// an initial value can be provided assert [].sum(1000) == 1000 assert [1, 2, 3].sum(1000) == 1006
def list = [1, 2] list.add(3) list.addAll([5, 4]) assert list == [1, 2, 3, 5, 4]
list = [1, 2] list.add(1, 3) // add 3 just before index 1 assert list == [1, 3, 2]
list.addAll(2, [5, 4]) //add [5,4] just before index 2 assert list == [1, 3, 5, 4, 2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g'] list[8] = 'x'// the [] operator is growing the list as needed // nulls inserted if required assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
def list = [1,2,3,4,3,2,1] list -= 3// creates a new list by removing `3` from the original one assert list == [1,2,4,2,1] assert ( list -= [2,4] ) == [1,1]
同样,你也能通过索引的方式从list里删除元素.
1 2 3
def list = [1,2,3,4,5,6,2,2,1] assert list.remove(2) == 3// remove the third element, and return it assert list == [1,2,4,5,6,2,2,1]
假设,你如果从list中删除多个相同元素中的第一个, 那你可以调用remove方法.
1 2 3 4 5 6
def list= ['a','b','c','b','b'] assert list.remove('c') // remove 'c', and return true because element removed assert list.remove('b') // remove first 'b', and return true because element removed
assert ! list.remove('z') // return false because no elements removed assert list == ['a','b','b']
如果你想要将list清空的话,只需要调用clear方法即可
1 2 3
def list= ['a',2,'c',4] list.clear() assert list == []
Set operations
Groovy development kit还包含很多逻辑运算的方法
1 2 3 4 5 6 7 8 9 10 11 12 13
assert'a'in ['a','b','c'] // returns true if an element belongs to the list assert ['a','b','c'].contains('a') // equivalent to the `contains` method in Java assert [1,3,4].containsAll([1,4]) // `containsAll` will check that all elements are found
assert [1,2,3,3,3,3,4,5].count(3) == 4// count the number of elements which have some value assert [1,2,3,3,3,3,4,5].count { it%2==0// count the number of elements which match the predicate } == 2
1 This time, we surround the key variable with parentheses, to instruct the parser we are passing a variable rather than defining a string key 2 The map does contain the name key 3 But the map doesn’t contain the key key as before 1. 2. 3.
def entries = map.entrySet() entries.each { entry -> assert entry.key in [1,2,3] assert entry.value in ['a','b','c'] }
def keys = map.keySet() assert keys == [1,2,3] as Set
Mutating values returned by the view (be it a map entry, a key or a value) is highly discouraged because success of the operation directly depends on the type of the map being manipulated. In particular, Groovy relies on collections from the JDK that in general make no guarantee that a collection can safely be manipulated through keySet, entrySet, or values.
Filtering and searching
The Groovy development kit contains filtering, searching and collecting methods similar to those found for lists:
def bob = people.find { it.value.name == 'Bob' } // find a single entry def females = people.findAll { it.value.gender == 'F' }
// both return entries, but you can use collect to retrieve the ages for example def ageOfBob = bob.value.age def agesOfFemales = females.collect { it.value.age }
// but you could also use a key/pair value as the parameters of the closures def agesOfMales = people.findAll { id, person -> person.gender == 'M' }.collect { id, person -> person.age } assert agesOfMales == [32, 36]
// `every` returns true if all entries match the predicate assert people.every { id, person -> person.age > 18 }
// `any` returns true if any entry matches the predicate
assert people.any { id, person -> person.age == 54 }
Grouping
We can group a list into a map using some criteria:
// an inclusive range def range = 5..8 assert range.size() == 4 assert range.get(2) == 7 assert range[2] == 7 assert range instanceof java.util.List assert range.contains(5) assert range.contains(8)
// lets use a half-open range range = 5..<8 assert range.size() == 3 assert range.get(2) == 7 assert range[2] == 7 assert range instanceof java.util.List assert range.contains(5) assert !range.contains(8)
//get the end points of the range without using indexes range = 1..10 assert range.from == 1 assert range.to == 10
Note that int 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. For example, you can create a range of String elements: