1.GPath 支持
由于对列表和映射的属性表示法的支持,Groovy 提供了语法糖,使得处理嵌套集合变得非常容易,如下面的示例所示:
def listOfMaps = [['a': 11, 'b': 12], ['a': 21, 'b': 22]]
assert listOfMaps.a == [11, 21] // GPath符号
assert listOfMaps*.a == [11, 21] // 扩展点表示法
listOfMaps = [['a': 11, 'b': 12], ['a': 21, 'b': 22], null]
assert listOfMaps*.a == [11, 21, null] // 空entry
assert listOfMaps*.a == listOfMaps.collect { it?.a } // 等效符号
// 但这只会收集非空值
assert listOfMaps.a == [11,21]
2.扩展运算符
扩展运算符可用于将一个集合“内联”到另一个集合中。它是语法糖,通常避免调用putAll并促进单行代码的实现:
assert [
'z': 900,
*: ['a': 100, 'b': 200],
'a': 300,
] == [
'a': 300,
'b': 200,
'z': 900,
]
// Map中的扩展地图符号
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',
]
// 函数参数中的扩展映射表示法
f = { map -> map.c }
assert f(*: ['a': 10, 'b': 20, 'c': 30], 'e': 50) == 30
f = { m, i, j, k -> [m, i, j, k] }
//将扩展映射表示法与未命名和命名参数混合使用
assert f('e': 100, *[4, 5], *: ['a': 10, 'b': 20, 'c': 30], 6) ==
[["e": 100, "b": 20, "c": 30, "a": 10], 4, 5, 6]
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
4.下标运算符切片
您可以使用下标表达式对列表、数组、地图进行索引。有趣的是,在这种情况下,字符串被视为特殊类型的集合:
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']
值得注意的是,允许负索引,以便更容易地从集合的末尾提取:
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"