《Groovy官方文檔》Groovy開發套件-使用集合
原文鏈接 譯文鏈接 譯者:JackWang
Groovy開發套件 第二部分
2 使用集合
Groovy提供了各種類型的原生態集合支持,包括 list , maps 和 ranges 。它們大多數都是基于Java集合類型,同時在Java集合類型中一些廢棄的方法在 Groovy開發套件 中也可以找到。
2.1 Lists
2.1.1 list 基本用法
(譯者注:原文是list literals,直譯可以翻譯為list字面意思,從下文內容來看指的就是list創建和獲取元素,譯者意譯為list基本用法)
你可以使用如下方式創建一個list,注意[]是一個空list表達式。
def list = [5, 6, 7, 8]
assert list.get(2) == 7
assert list[2] == 7
assert list instanceof java.util.List
def emptyList = []
assert emptyList.size() == 0
emptyList.add(5)
assert emptyList.size() == 1
每一個list表達式都是 java.util.list 的一個實現。
當然,lists也可以用于構造另外一個list:
def list1 = ['a', 'b', 'c']
//construct a new list, seeded with the same items as in list1
def list2 = new ArrayList(list1)
assert list2 == list1 // == checks that each corresponding element is the same
// clone() can also be called
def list3 = list1.clone()
assert list3 == list1
list是一個序列集合的對象(譯者注:原文是A list is an ordered collection of objects,從下文的示例代碼來看,這里不是有序的意思,而是相當于Java集合里的ArrayList,因此認為翻譯為序列比有序更為恰當):
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, 9 as byte]
//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()
assert false
} catch (e) {
assert e instanceof ArrayIndexOutOfBoundsException
}
2.1.2 list作為一個boolean表達式
List可以當作一個boolean值:
assert ![] // an empty list evaluates as false
//all other lists, irrespective of contents, evaluate as true
assert [1] && ['a'] && [0] && [0.0] && [false] && [null]
2.1.3 list迭代
迭代一個list上的元素可以使用each和eachWithIndex方法,示例代碼如下:
[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"
}
除了上面的用法,通過使用迭代,還可以將某些元素轉換為另外一種元素來創建一個新的集合。這也是非常有用的用法。這樣的操作,通常叫做映射。在Groovy里可以使用collect方法:
assert [1, 2, 3].collect { it * 2 } == [2, 4, 6]
// shortcut syntax instead of collect
assert [1, 2, 3]*.multiply(2) == [1, 2, 3].collect { it.multiply(2) }
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]
2.1.4 操作lists
過濾和搜索
Groovy開發套件 在集合操作上提供了許多方法來拓展標準集合,一些方法示例如下:
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
assert [1, 2, 3].join(‘-‘) == ‘1-2-3′ // String joining
assert [1, 2, 3].inject(‘counting: ‘) {
str, item -> str + item // reduce operation
} == ‘counting: 123′
assert [1, 2, 3].inject(0) { count, item ->
count + item
} == 6
下面是使用Groovy在集合中查找最大最小值的標準代碼:
def list = [9, 4, 2, 10, 5]
assert list.max() == 10
assert list.min() == 2
// we can also compare single characters, as anything comparableassert [‘x’, ‘y’, ‘a’, ‘z’].min() == ‘a’
// we can use a closure to specify the sorting behaviour
def list2 = [‘abc’, ‘z’, ‘xyzuvw’, ‘Hello’, ‘321’]
assert list2.max { it.size() } == ‘xyzuvw’
assert list2.min { it.size() } == ‘z’
除了使用閉包,你可以使用Comparator來定義一個比較:
Comparator mc = { a, b -> a == b ? 0 : (a a == b ? 0 : (Math.abs(a) a.equals(b) ? 0 : Math.abs(a) a.equals(b) ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1 } == -1
添加或刪除元素
我們可以使用[]來創建一個新的空list,使用<<來追加元素在里面:
def list = []
assert list.empty
list << 5
assert list.size() == 1
list << 7 << 'i' << 11
assert list == [5, 7, 'i', 11]
list << ['m', 'o']
assert list == [5, 7, 'i', 11, ['m', 'o']]
//first item in chain of << is target list
assert ([1, 2] << 3 << [4, 5] << 6) == [1, 2, 3, [4, 5], 6]
//using leftShift is equivalent to using <<
assert ([1, 2, 3] << 4) == ([1, 2, 3].leftShift(4))
我們也可以使用下面的方法來添加元素:
assert [1, 2] + 3 + [4, 5] + 6 == [1, 2, 3, 4, 5, 6]
// equivalent to calling the `plus` method
assert [1, 2].plus(3).plus([4, 5]).plus(6) == [1, 2, 3, 4, 5, 6]
def a = [1, 2, 3]
a += 4 // creates a new list and assigns it to `a`
a += [5, 6]
assert a == [1, 2, 3, 4, 5, 6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [*[1, 2, 3]] == [1, 2, 3]
assert [1, [2, 3, [4, 5], 6], 7, [8, 9]].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
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']
特別重要的是+操作不能改變一個集合。和<<相比,它會創建一個新的list,這可能通常不是你想要的結果,同時會有性能問題。(譯者注:這里和Java中String類型的+操作類似)
Groovy開發套件提供了下面的方法來輕松實現從集合中刪除元素:
assert ['a','b','c','b','b'] - 'c' == ['a','b','b','b']
assert ['a','b','c','b','b'] - 'b' == ['a','c']
assert ['a','b','c','b','b'] - ['b','c'] == ['a']
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]
也可以使用下標操作來刪除元素,這樣會使原集合發生改變:
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]
有時候你僅僅想刪除第一次出現的元素,而不是刪除全部匹配的元素,你可以這樣是使用remove方法:
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方法:
def list= ['a',2,'c',4]
list.clear()
assert list == []
Set操作
Groovy開發套件同樣也提供了許多方法來方便進行Sets操作
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
assert [1,2,4,6,8,10,12].intersect([1,3,6,9,12]) == [1,6,12]
assert [1,2,3].disjoint( [4,6,9] )
assert ![1,2,3].disjoint( [2,4,6] )
排序
使用Collections的排序,Groovy提供了許多參數來排序一個lists,從使用閉包到使用比較器,示例代碼如下:
assert [6, 3, 9, 2, 7, 1, 5].sort() == [1, 2, 3, 5, 6, 7, 9]
def list = ['abc', 'z', 'xyzuvw', 'Hello', '321']
assert list.sort {
it.size()
} == ['z', 'abc', '321', 'Hello', 'xyzuvw']
def list2 = [7, 4, -6, -1, 11, 2, 3, -9, 5, -13]
assert list2.sort { a, b -> a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1 } == [-1, 2, 3, 4, 5, -6, 7, -9, 11, -13] Comparator mc = { a, b -> a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1 }
// JDK 8+ only
// list2.sort(mc)
// assert list2 == [-1, 2, 3, 4, 5, -6, 7, -9, 11, -13]
def list3 = [6, -3, 9, 2, -7, 1, 5]
Collections.sort(list3)
assert list3 == [-7, -3, 1, 2, 5, 6, 9]
Collections.sort(list3, mc)
assert list3 == [1, 2, -3, 5, 6, -7, 9]
復制元素
Groovy開發套件重載了一些操作來對集合進行復制操作:
assert [1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]
assert [1, 2, 3].multiply(2) == [1, 2, 3, 1, 2, 3]
assert Collections.nCopies(3, 'b') == ['b', 'b', 'b']
// nCopies from the JDK has different semantics than multiply for lists
assert Collections.nCopies(2, [1, 2]) == [[1, 2], [1, 2]] //not [1,2,1,2]
2.2 Maps
2.2.1 Map基本操作
在Groovy里,maps(通常和arrays聯系在一起)可以使用 [:] 來創建:
def map = [name: 'Gromit', likes: 'cheese', id: 1234]
assert map.get('name') == 'Gromit'
assert map.get('id') == 1234
assert map['name'] == 'Gromit'
assert map['id'] == 1234
assert map instanceof java.util.Map
def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.put("foo", 5)
assert emptyMap.size() == 1
assert emptyMap.get("foo") == 5
Map的key默認是字符串類型的,[a:1]和[‘a’:1]是等效的。如果你的變量名字恰好也是a 那就會導致混亂了,可能你是想將 a 的值作為你map的key。如果是這種情況,你必須使用括號來轉義,類似下面的例子:
def a = 'Bob'
def ages = [a: 43]
assert ages['Bob'] == null // `Bob` is not found
assert ages['a'] == 43 // because `a` is a literal!
ages = [(a): 43] // now we escape `a` by using parenthesis
assert ages['Bob'] == 43 // and the value is found!
除了map的基本操作,要得到一個map的新的拷貝,可以clone它:
def map = [
simple : 123,
complex: [a: 1, b: 2]
]
def map2 = map.clone()
assert map2.get('simple') == map.get('simple')
assert map2.get('complex') == map.get('complex')
map2.get('complex').put('c', 3)
assert map.get('complex').get('c') == 3
上面的例子得到的就是原始map的一個投影。
2.2.2 Map屬性標記
Maps可以像你操作Bean那樣通過使用屬性標記來get/set Map內部的元素。只要key是Groovy識別的字符串:
def map = [name: 'Gromit', likes: 'cheese', id: 1234]
assert map.name == 'Gromit' // can be used instead of map.get('Gromit')
assert map.id == 1234
def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.foo = 5
assert emptyMap.size() == 1
assert emptyMap.foo == 5
注意:默認情況下map.foo將總是在map中搜索key為foo的元素。這意味著如果一個map鐘不含有class的可以,foo.class將會返回null。如果你只是想知道類類型,你必須使用getClass() :
def map = [name: 'Gromit', likes: 'cheese', id: 1234]
assert map.class == null
assert map.get('class') == null
assert map.getClass() == LinkedHashMap // this is probably what you want
map = [1 : 'a',
(true) : 'p',
(false): 'q',
(null) : 'x',
'null' : 'z']
assert map.containsKey(1) // 1 is not an identifier so used as is
assert map.true == null
assert map.false == null
assert map.get(true) == 'p'
assert map.get(false) == 'q'
assert map.null == 'z'
assert map.get(null) == 'x'
2.2.3 Maps的迭代
通常在Groovy開發套件里,迭代map是用each和eachWithIndex方法。maps的創建也是序列的,也就是說當你迭代一個map的時候,可以保證迭代的順序就是添加元素的順序:
def map = [
Bob : 42,
Alice: 54,
Max : 33
]
// `entry` is a map entry
map.each { entry ->
println "Name: $entry.key Age: $entry.value"
}
// `entry` is a map entry, `i` the index in the map
map.eachWithIndex { entry, i ->
println "$i - Name: $entry.key Age: $entry.value"
}
// Alternatively you can use key and value directly
map.each { key, value ->
println "Name: $key Age: $value"
}
// Key, value and i as the index in the map
map.eachWithIndex { key, value, i ->
println "$i - Name: $key Age: $value"
}
2.2.4 操作maps
添加或刪除元素
添加一個元素到map可以使用put,批量操作可以使用putAll:
def defaults = [1: 'a', 2: 'b', 3: 'c', 4: 'd']
def overrides = [2: 'z', 5: 'x', 13: 'x']
def result = new LinkedHashMap(defaults)
result.put(15, 't')
result[17] = 'u'
result.putAll(overrides)
assert result == [1: 'a', 2: 'z', 3: 'c', 4: 'd', 5: 'x', 13: 'x', 15: 't', 17: 'u']
刪除一個map鐘全部元素可以使用clear方法:
def m = [1:'a', 2:'b']
assert m.get(1) == 'a'
m.clear()
assert m == [:]
使用map基本操作生成的map使用了對象的equals和hashcode方法。這個意味著你不應該使用一個hash code經常改變的對象或者其值不可逆操作的對象放入map。
你使用一個GString來作為map的key也是沒有意義的。因為GString的hashcode和String的hashcode并不相等。
def key = 'some key'
def map = [:]
def gstringKey = "${key.toUpperCase()}"
map.put(gstringKey,'value')
assert map.get('SOME KEY') == null
keys,values和entries
我們可以在一個視圖里查看keys,values和entries:
def map = [1:'a', 2:'b', 3:'c']
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
通過視圖(也就是map的key,entry和value)返回的值來操作values是強烈不推薦的方式。因為maps操作已經有很多直接操作的方法。特別地,Groovy依賴于JDK的一些方法并不保證能夠安全地操作集合,比如keySet,entrySet或values
過濾和搜索
Groovy開發套件包含過濾,搜索集合方法,這個和 list 是類似的:
def people = [
1: [name:'Bob', age: 32, gender: 'M'],
2: [name:'Johnny', age: 36, gender: 'M'],
3: [name:'Claire', age: 21, gender: 'F'],
4: [name:'Amy', age: 54, gender:'F']
]
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
}
assert ageOfBob == 32
assert agesOfFemales == [21,54]
// 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
}
分組
我們可以將一個list按某些維度分組到一個map中:
assert ['a', 7, 'b', [2, 3]].groupBy {
it.class
} == [(String) : ['a', 'b'],
(Integer) : [7],
(ArrayList): [[2, 3]]
]
assert [
[name: 'Clark', city: 'London'], [name: 'Sharma', city: 'London'],
[name: 'Maradona', city: 'LA'], [name: 'Zhang', city: 'HK'],
[name: 'Ali', city: 'HK'], [name: 'Liu', city: 'HK'],
].groupBy { it.city } == [
London: [[name: 'Clark', city: 'London'],
[name: 'Sharma', city: 'London']],
LA : [[name: 'Maradona', city: 'LA']],
HK : [[name: 'Zhang', city: 'HK'],
[name: 'Ali', city: 'HK'],
[name: 'Liu', city: 'HK']],
]
2.3 Ranges(區間)
Ranges允許你創建一個序列值得list,它可以當成list用,因為 Range 繼承了 java.util.List
Ranges定義使用 .. 代表閉區間(包括起點和終點)
Ranges定義使用 ..< 代表一個半開半閉,只包含第一個值不包含最后一個值。
// 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
可以看到創建一個int區間是非常高效的,可以創建一個非常輕量級的包含起點值和終點值得對象。
區間也可以用作實現了Java.lang.Comparable接口作為比較器的任何Java對象。可以使用next()和previous()來返回netx/previous元素。舉個例子,你可以創建一個String元素類型的區間:
// an inclusive range
def range = 'a'..'d'
assert range.size() == 4
assert range.get(2) == 'c'
assert range[2] == 'c'
assert range instanceof java.util.List
assert range.contains('a')
assert range.contains('d')
assert !range.contains('e')
你可以使用for循環來迭代區間元素:
for (i in 1..10) {
println "Hello ${i}"
}
當然你也可以使用更加Groovy風格的方式來實現同樣的效果,通過使用each方法來迭代區間元素:
(1..10).each { i ->
println "Hello ${i}"
}
區間同樣可以用在switch語句中:
switch (years) {
case 1..10: interestRate = 0.076; break;
case 11..25: interestRate = 0.052; break;
default: interestRate = 0.037;
}
2.4 Collections的語法增強
2.4.1 GPath支持
幸虧屬性標記對Lists和Maps都支持,Groovy 提供了非常實用的方法來使嵌套集合處理變得非常簡潔,示例代碼如下:
def listOfMaps = [['a': 11, 'b': 12], ['a': 21, 'b': 22]]
assert listOfMaps.a == [11, 21] //GPath notation
assert listOfMaps*.a == [11, 21] //spread dot notation
listOfMaps = [[‘a': 11, ‘b': 12], [‘a': 21, ‘b': 22], null]
assert listOfMaps*.a == [11, 21, null] // caters for null values
assert listOfMaps*.a == listOfMaps.collect { it?.a } //equivalent notation
// But this will only collect non-null values
assert listOfMaps.a == [11,21]
2.4.2 Spread操作
Spread操作可以認為是將一個集合內聯到另外一個集合。這樣就可以避免使用putAll方法從而將實現變得只要一行代碼:
assert [ 'z': 900,
*: ['a': 100, 'b': 200], 'a': 300] == ['a': 300, 'b': 200, 'z': 900]
//spread map notation in map definition
assert [*: [3: 3, *: [5: 5]], 7: 7] == [3: 3, 5: 5, 7: 7]
def f = { [1: ‘u’, 2: ‘v’, 3: ‘w’] }
assert [*: f(), 10: ‘zz’] == [1: ‘u’, 10: ‘zz’, 2: ‘v’, 3: ‘w’]
//spread map notation in function arguments
f = { map -> map.c }
assert f(*: [‘a': 10, ‘b': 20, ‘c': 30], ‘e': 50) == 30
f = { m, i, j, k -> [m, i, j, k] }
//using spread map notation with mixed unnamed and named arguments
assert f(‘e': 100, *[4, 5], *: [‘a': 10, ‘b': 20, ‘c': 30], 6) ==
[[“e”: 100, “b”: 20, “c”: 30, “a”: 10], 4, 5, 6]
2.4.3 星號操作 *
星號操作是允許你在一個集合的全部元素中調用某個方法或屬性的簡潔操作:
assert [1, 3, 5] == ['a', 'few', 'words']*.size()
class Person {
String name
int age
}
def persons = [new Person(name:'Hugo', age:17), new Person(name:'Sandra',age:19)]
assert [17, 19] == persons*.age
2.4.4 使用下標操作來分片
你可以使用下標來索引lists,arrays,maps。字符串類型被當成一種特殊的集合類型:
def text = 'nice cheese gromit!'
def x = text[2]
assert x == ‘c’assert x.class == String
def sub = text[5..10]assert sub == ‘cheese’
def list = [10, 11, 12, 13]
def answer = list[2,3]
assert answer == [12,13]
注意你可以使用區間來提取集合:
list = 100..200
sub = list[1, 3, 20..25, 33]
assert sub == [101, 103, 120, 121, 122, 123, 124, 125, 133]
下標操作也可以用于更新已有集合(對于那些不可變集合)
list = ['a','x','x','d']
list[1..2] = ['b','c']
assert list == ['a','b','c','d']
值得注意的是負數也是被允許的,表示從集合后面提取元素:你可以使用負數來表示從尾開始操作list,array,String等:
text = "nice cheese gromit!"
x = text[-1]
assert x == "!"
def name = text[-7..-2]assert name == “gromit”
同樣地,如果你使用一個反向區間(起點下標大于終點下標),結果也會是反的。
text = "nice cheese gromit!"
name = text[3..1]
assert name == "eci"
2.5 增強的集合方法
對于 list , maps 和 ranges ,Groovy提供了許多額外的方法來過濾,集合分組,技術等等,那些方法使集合操作更加簡單,迭代操作更加容易。
特別地,我們希望你能特別地讀一下Groovy開發套件的API文檔:
- Iterable額外的方法可以在 這里找到
- Iterator額外的方法可以在 這里找到
- Collection額外的方法可以在 這里找到
- List額外的方法可以在 這里找到
- Map額外的方法可以在 這里找到
3 有用的工具類
3.1 ConfigSlurper
ConfigSlurper是用來讀配置文件的工具類,通常是Grooy腳本格式的配置文件。類似于Java里的*.properties文件。ConfigSlurper允許點操作符,除此之外,還允許閉包操作配置值和一些對象類型
def config = new ConfigSlurper().parse('''
app.date = new Date() (1)
app.age = 42
app { (2)
name = "Test${42}"
}
''')
assert config.app.date instanceof Date
assert config.app.age == 42
assert config.app.name == 'Test42'
(1)使用點操作符
(2)使用閉包來代替點操作符
從上面的例子可以看到,parse方法可以用來返回groovy.util.ConfigObject實例,ConfigObject是一種特別的java.util.Map實現。既可以用于返回配置值,也可以返回一個不為null的新的ConfigObject實例對象
def config = new ConfigSlurper().parse('''
app.date = new Date()
app.age = 42
app.name = "Test${42}"
''')
assert config.test != null //(1)
(1)config.test還沒有被實例化因此當被調用的時候將會返回一個ConfigObject
如果點號是配置文件值的一部分,可以使用單引號或雙引號將其轉義。
def config = new ConfigSlurper().parse('''
app."person.age" = 42
''')
assert config.app."person.age" == 42
除此之外,ConfigSlurper也支持environments . enviroments方法可以被用來處理閉包實例,它自身也有可能由好幾個部分組成。假如說我們想創建一個特定的配置值來給開發環境用,當我們創建一個 ConfigSlurper實例的時候我們可以使用ConfigSlurper(String)構造函數來實現特定環境的配置.
def config = new ConfigSlurper('development').parse('''
environments {
development {
app.port = 8080
}
test {
app.port = 8082
}
production {
app.port = 80
}
}
''')
assert config.app.port == 8080
ConfigSlurper環境變量沒有嚴格遵循任何環境變量名字。取決于特定的ConfigSlurper客戶端代碼。
enviroments方法是一個那只方法,但是registerConditionalBlock方法可以用于注冊其他方法名字,并且可以是enviroments名字。
def slurper = new ConfigSlurper()
slurper.registerConditionalBlock('myProject', 'developers') (1)
def config = slurper.parse('''sendMail = true
myProject {
developers {
sendMail = false
}
}
''')
assert !config.sendMail
(1)一旦一個新的塊注冊了,ConfigSlurper可以編碼它
因為Java集成原因,toProperties方法可以用于將ConfigObject對象轉換到 java.util.Properties對象。然后可以將其存在*.properties文本文件中。注意,在新建一個Properties實例的時候配置值將會轉換為String類型實例。
def config = new ConfigSlurper().parse('''
app.date = new Date()
app.age = 42
app {
name = "Test${42}"
}
''')
def properties = config.toProperties()
assert properties."app.date" instanceof String
assert properties."app.age" == '42'
assert properties."app.name" == 'Test42'
3.2 Expando
Expando類可以用于動態創建可拓展對象。盡管它的類名沒有采用ExpandoMetaClass。每一個Expando對象代表一個獨立的動態的實例,可以在運行時被屬性或方法所拓展
def expando = new Expando()
expando.name = 'John'
assert expando.name == 'John'
一個特殊的例子是當一個動態屬性注冊到一個閉包代碼塊。一個注冊就可以被方法所動態調用:
def expando = new Expando()
expando.toString = { -> 'John' }
expando.say = { String s -> "John says: ${s}" }
assert expando as String == 'John'
assert expando.say('Hi') == 'John says: Hi'
3.3 可觀察的list,map和set
Groovy提供了可觀察的lists,maps和sets。每一個都是一個 java.beans.propertyChangeEvnent事件的觸發器。當元素被添加,刪除,修改就會被觸發。注意 PropertyChangeEvent不僅僅當某些事件發生才出發,同時可以保存新舊值。
可能會有類型改變,可觀察的集合可能需要更加特別的PropertyChangeEvnet類型。比如當添加一個元素到可觀察list觸發一個ObservableList.ElementAddedEvent事件。
def event (1)
def listener = {
if (it instanceof ObservableList.ElementEvent) { (2)
event = it
}
} as PropertyChangeListener
def observable = [1, 2, 3] as ObservableList (3)observable.addPropertyChangeListener(listener) (4)
observable.add 42 (5)
assert event instanceof ObservableList.ElementAddedEvent
def elementAddedEvent = event as ObservableList.ElementAddedEvent
assert elementAddedEvent.changeType == ObservableList.ChangeType.ADDED
assert elementAddedEvent.index == 3
assert elementAddedEvent.oldValue == null
assert elementAddedEvent.newValue == 42
(1)聲明一個PropertyChangeEventListener可以捕捉觸發事件
(2)ObservableList.ElementEvent和它的相關類型是相對與這個監聽器
(3)注冊一個監聽器
(4)從給定的list創建一個ObservableList
(5)ObservableList.ElementAddedEvent事件的觸發器
注意,添加一個元素將會觸發兩個事件,第一個是ObservableList.ElementAddedEvent 第二個是 PropertyChangeEvent,用來通知監聽器這次修改屬性的size
ObservableList.ElementClearedEvent 事件類型是另外一個有趣的事件。無論什么時候多個元素被刪除,比如當我們調用clear()方法的時候,它將會保存被刪除的元素
def event
def listener = {
if (it instanceof ObservableList.ElementEvent) {
event = it
}
} as PropertyChangeListener
def observable = [1, 2, 3] as ObservableListobservable.addPropertyChangeListener(listener)
observable.clear()
assert event instanceof ObservableList.ElementClearedEvent
def elementClearedEvent = event as ObservableList.ElementClearedEvent
assert elementClearedEvent.values == [1, 2, 3]
assert observable.size() == 0
為了了解整個事件類型,建議讀者閱讀JavaDoc文檔或可觀察集合的源碼。
這個章節里,ObservableMap和ObservableSet是同一個概念,和我們見過的ObservableList一樣。