最近项目用到了groovy对map的数据进行加工,贴一下学习总结。
groovy的特点
同时支持静态和动态类型。
支持运算符重载。
本地语法列表和关联数组。
对正则表达式的本地支持。
各种标记语言,如XML和HTML原生支持。
Groovy对于Java开发人员来说很简单,因为Java和Groovy的语法非常相似。
使用java方法遍历map
```groovy
def map=['getInfo':['getPersonInfo':['name':'eric','age':18],'getCompanyInfo':['name':'my company','HR':30]]];
println map.getInfo.getCompanyInfo.name;
def infoMap=map.getInfo.getPersonInfo;
println infoMap;
println "第一种";
for ( key : infoMap.keySet()) {
println("key= "+ key + " and value= " + infoMap.get(key));
}
println "第二种";
Iterator<Map.Entry<String, String>> it = infoMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
println "第三种";
for (Map.Entry<String, String> entry : infoMap.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
println "第四种";
for (String v : infoMap.values()) {
System.out.println("value= " + v);
}
```
用groovy的特性遍历map
```groovy
println "第一种"
def map = [
'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'
]
map.each{ k, v -> println "${k}:${v}" }
println "第二种"
def map = ['a':1, 'b':2, 'c':3]
for ( e in map ) {
print " key = ${e.key}, value = ${e.value}"
}
def groovyMap = [B: "Benz", "L": "Lexus", A: "Audi"]
println "groovyMap type is : " + groovyMap.getClass()
println "groovyMap.B value is : ${groovyMap.B}"
println "groovyMap.'B' value is : ${groovyMap.'B'}"
println "groovyMap['B'] value is : ${groovyMap['B']}"
groovyMap.F = 'Ferrari'
groovyMap << [P:"Porsche"]
groovyMap.each {
print "${it} "
}
println "\nkey-value接收遍历"
groovyMap.each {
key , value ->
print "key = ${key} , value = ${value}"
}
println "\n展开操作符获取key集合"
def getKey = groovyMap*.getKey()
println "getKey is : ${getKey}"
```