First they ignore you
then they ridicule you
then they fight you
then you win
    -- Mahatma Gandhi
Chinese => English     英文 => 中文             
随笔-221  评论-1047  文章-0  trackbacks-0
将对象组织到像列表和映射这样的数据结构中是一项基本的编码任务。像大多数语言一样,Groovy 定义了一个丰富的库以管理这些类型的集合。

列表

创建一个列表与在 Java 语言中创建一个数组很类似。

collect = ['groovy', 29, 'Hello', 'Groovy']

empty=[]
assert empty.size() == 0
//添加元素
empty.add 1
assert empty.size() == 2

在上面的例子里,列表 collect 的第二项自动装箱为一个 Integer 类型。此外“[]”表示一个空列表,这个例子还演示了如何向列表中添加元素。

Groovy 还为集合增加了几个新方法,这些方法使得对列表的一些操作变得更加容易,如统计值出现的次数、将整个列表结合到一起、对列表排序等等。可以在例2 中看到这些集合方法的使用。

collect = [5, 9, 2, 2, 4, 5, 6] 
println collect.join(' - ') // prints 5 - 9 - 2 - 2 - 4 - 5 - 6
println collect.count(2) // prints 2
println collect.sort() // prints [2, 2, 4, 5, 5, 6, 9]

Maps

像列表一样,映射也是一种在 Groovy 中非常容易处理的数据结构。例 3 中的映射包含两个对象,键是 name 和 date。注意可以用不同的方式取得值。 可以用“[:]”创造一个空的映射。

myMap = ["name" : "Groovy", "date" : new Date()]
println myMap["date"]
println myMap.date

Map可以象beans一样操作,但key值(类似属性名)必须为有效的String标识。下面的例子详细演示了Map的用法。

map = ["name":"Gromit", "likes":"cheese", "id":1234]
assert map.name == "Gromit"
assert map.id == 1234
//Create an empty maps
emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.foo = 5
assert emptyMap.size() == 1
assert emptyMap.foo == 5
emptyMap.put("bar",6)
assert emptyMap.get("bar") == 6

players = ['baseball':'Albert Pujols', 'golf':'Tiger Woods']
println players['golf'] // prints Tiger Woods
println players.golf // prints Tiger Woods
for (player in players)
{
println "${player.value} plays ${player.key}"
}
// This has the same result as the previous loop.
players.each {
player |println "${player.value} plays ${player.key}"
}

范围

范围(Range)是Groovy的一大亮点Range允许创建连续值的列表。范围是一个很直观的概念,并且容易理解,利用它可以包含地或者排除地创建一 组有序值。使用“..”的Range是包括两个边界,使用“..<”(Groovy Beta3使用 “...”)的Range只包括开始边界,而不包括结束边界。

而且由于Range扩展java.util.List,所以Range可以作为List使用。

myRange = 29..<32
myInclusiveRange = 2..5
println myRange.size() // prints 3
println myRange[0] // prints 29
println myRange.contains(32) //prints false
println myInclusiveRange.contains(5) //prints true

// an inclusive range and operations
range = 'a'..'d'
assert range.size() == 4
assert range.get(2) == 'c'
assert range instanceof java.util.List
assert range.contains('a')
assert range.contains('d')
assert ! range.contains('e')

迭代器

迭代是各种编程环境中最常见、最有用的技术。迭代器可以让您迅速地访问任何集合或容器中的数据,每次一个数据。Groovy 把迭代器变成隐含的,使用起来更简单,从而改善了 Java 语言的迭代器概念。

我们可以直接在集合上使用类似迭代器的方法。而且, Groovy 的迭代器方法接受闭包,每个迭代中都会调用闭包。

class IteratorExample1{
static void main(args) {
coll = ["JMS", "EJB", "JMX"]
coll.each{ item | println item }
}
}

范围可以用于循环遍历。例如,将 rang 定义为一个排除范围,循环打印 a、b、c 和 d。

aRange = 'a'..<'e'
for (i in aRange){
println i
}

集合的其他功能

如果不熟悉 Python 和其他脚本语言,那么您在 Groovy 集合中发现的一些其他功能会让您印象深刻。例如,创建了集合后,可以用负数在列表中反向计数:

aList = ['python', 'ruby', 'groovy']
println aList[-1] // prints groovy
println aList[-3] // prints python

Groovy 还让您可以用范围分割列表。分割可获得列表的准确子集:

fullName = "Andrew James Glover"
mName = fullName[7..<13]
println "middle name: " + mName // prints James

Ruby的语法

集合类似于 Ruby如果愿意的话,还可以将 Groovy 集合作为 Ruby 集合。可以用类似 Ruby 的语法,以 << 语法附加元素、用 + 串接和用 - 对集合取差,甚至还可以用 * 语法处理集合的重复。 注意,还可以用 == 比较集合。

collec = [1, 2, 3, 4, 5]
collec << 6 //appended 6 to collec

acol = ['a','b','c'] * 3 //acol now has 9 elements
coll = [10, 11]
coll2 = [12, 13]
coll3 = coll + coll2 //10,11,12,13
difCol = [1,2,3] - [1,2] //difCol is 3
assert [1, 2, 3] == [1, 2, 3] //true

集合的索引

可以在字符串、Lists、Maps...中使用下标进行索引

text = "nice cheese gromit!"
x = text[2]
assert x == "c"
assert x.class == String

sub = text[5..10]
assert sub == 'cheese'

map = ["name":"Gromit", "likes":"cheese", "id":1234]
assert map['name'] == "Gromit"

list = [10, 11, 12]
answer = list[2]
assert answer == 12
list = 100..200
sub = list[1, 3, 20..25, 33]
assert sub == [101, 103, 120, 121, 122, 123, 124, 125, 133]

可以使用下标操作符更新项目:

list = ["a", "b", "c"]
list[2] = "d"
list[0] = list[1]
list[3] = 5
assert list == ["b", "b", "d", 5]

可以使用负索引从最后开始计数:

text = "nice cheese gromit!"
x = text[-1]
assert x == "!"
name = text[-7..-2]
assert name == "gromit"

也可以使用向后范围(开始索引大于结束索引),返回的结果是反转的

text = "nice cheese gromit!"
name = text[3..1]
assert name == "eci"

// 山风小子注:closure中的‘分隔符’应该为 -> 而不是|,后者已经被废弃。

原文地址:http://blogger.org.cn/blog/more.asp?name=lhwork&id=20812
附:
Groovy与Grails同甘共苦,苦尽甘来
posted on 2007-04-22 22:24 山风小子 阅读(1862) 评论(0)  编辑  收藏 所属分类: Groovy & Grails