方式一:Java方式
def map = new HashMap()
方式二:Groovy方式
def colors = ['red': '红色', 'green': '绿色', blue: '蓝色'] // 键可以不加单引号
注意:map的键必须指定为不可变的单引号字符串,如果没有给键指定单引号,编译器编译时会自动加上(就是键直接写值,而不用加上单引号)
map默认的是LinkedHashMap,如果我们想要指定集合类型,可以将def关键字替换为自己想要的map类型,例如
如果我想要指定为Hashtable
HashMap colors = ['red': '红色', 'green': '绿色', 'blue': '蓝色']
或者使用 as关键字,完成指定map类型
def colors = ['red': '红色', 'green': '绿色', 'blue': '蓝色'] as Hashtable
colors.getAt("red")
println colors['red']
colors.red
colors.put("yellow", "黄色")
colors.yellow = 'fff00'
colors.leftShift(["棕色": 'brown'])
注意:传入的是一个map集合
colors.complex = ["a": 3, "b": 5]
注:在map集合中获取类属性必须使用getClass方法,而不能使用.class方式获取了
使用remove方法,该方法有两个重载方法,第一个重载方法只需要一个参数,就是集合的键;第二个重载方法需要两个参数,分别为key与value,根据键值对删除集合中的元素
colors.remove("green")
- Students.each {
- def student ->
- println "the key is ${student.key} and the value is ${student.value}"
- }
这种方式是根据Map集合中的Entry(键值对)进行遍历的,还可以根据key与value进行遍历,需要注意的是,key与value参数的顺序不能颠倒,否则会造成数据的错乱
- // 直接遍历key, value而不再是遍历entry
- Students.each { key, value ->
- println "the key is ${key} and , the value is ${value}"
- }
这个是带索引的遍历
- // 带索引的each遍历
- Students.eachWithIndex { def student, int index -> // 二者的顺序不能颠倒
- println "the index is ${index} , the key is ${student.key} , and the value is ${student.value}"
- }
这个方法同样页可以使用key与value的方式进行带索引的map集合遍历,使用eachWithIndex方法,但是同样index必须为最后一个参数,否则会造成数据错乱
- Students.eachWithIndex { def key, def value, int index -> // 三者的顺序不能颠倒
- println "the index is ${index} , the key is ${key} , and the value is ${value}"
- }
这个方法借助闭包找出符合闭包条件中的第一个元素
- def entry = Students.find { def student ->
- return student.value.score >= 60
- }
这个方法借助闭包找出符合闭包条件中的所有元素
- def entries = Students.findAll { def student ->
- return student.value.score <= 60
- }
这个方法借助闭包,统计符合闭包条件元素的个数,返回值为Integer
- // count统计方法
- def count = Students.count { def student ->
- return student.value.score >= 60 && student.value.sex == 'male'
- }
对集合进行过滤,生成的是符合条件元素的列表
- // 查询所有学生成绩大于等于60的名字
- def names = Students.findAll { def student ->
- return student.value.score >= 60
- }.collect { return it.value.name } // 对集合进行过滤,生成的是符合条件学生名字的列表
借助闭包,根据指定条件对Map集合进行分组
- // 根据成绩进行分组
- def group = Students.groupBy { def student ->
- return student.value.score >= 60 ? '及格' : '不及格'
- }
使用sort方法,根据闭包中定义的条件对Map集合进行排序
- def sort = Students.sort { def student1, def student2 ->
- Number score1 = student1.value.score
- Number score2 = student2.value.score
- return score1 == score2 ? 0 : score1 < score2 ? -1 : 1
- }
注意:list的sort排序方法是没有返回值的,而map中的sort方法是有返回值的,返回的是一个新的map集合