HashMap color = [red:"fff", green:"ggg"] //as HashMap
color.yellow = 'yyy'
println color['red']
println color.green
println color.getClass() //默认是: class java.util.LinkedHashMap
//添加元素
color['black'] = "hei"
color.white = "bai"
color.ls = [2, 3, "cjt"]
println color.toMapString()
color.each {k,v ->{
println "${k}=${v}"
}}
color.each {map ->{
println "${map.key}=${map.value}"
}}
println "-----------------"
//Map操作
def students = [
1: [no: '001', 'name': 'cjt1', "score": 87],
2: [no: '002', 'name': 'cjt2', "score": 55],
3: [no: '003', 'name': 'cjt3', "score": 93],
4: [no: '004', 'name': 'cjt4', "score": 67],
]
//遍历
students.each {
def stu -> println "key is ${stu.key}, value is ${stu.value}"
}
students.each {
key, value -> println "key is ${key}, value is ${value}"
}
//带索引的遍历
students.eachWithIndex {
def stu, int index -> println "index is ${index}, key is ${stu.key}, value is ${stu.value}"
}
students.eachWithIndex {
def key, value, int index -> println "index is ${index}, key is ${key}, value is ${value}"
}
println "--------find 找到满足条件的第1条---------"
println students.find {stu -> stu.value.score >58}
println "-----------------"
println students.findAll {stu -> stu.value.score >58 & stu.value.name == "cjt3"}
println "-----------------"
println students.findAll {stu -> stu.value.score >58 }.collect {return it.value.name}
println "-----------------"
def group = students.groupBy { stu -> return stu.value.score > 60 ? '及格' : "不及格" }
println group.toMapString()
//[及格:[1:[no:001, name:cjt1, score:87], 3:[no:003, name:cjt3, score:93], 4:[no:004, name:cjt4, score:67]], 不及格:[2:[no:002, name:cjt2, score:55]]]
def sortMap = students.sort { stu1, stu2 ->
return stu1.value.score < stu2.value.score ? -1 : 1
}
println sortMap.toMapString()
网友评论