Map声明
def myMap = [a:1, b:2, c:3] assert myMap.size() == 3 assert myMap['a'] == 1 def emptyMap = [:] assert emptyMap.size() == 0 def myMap2 = new TreeMap() myMap2.putAll(myMap) assert myMap2['a'] == 1
使用Map操作符
如果get(key,default)被调用时,key没有找到并且缺省值被返回,那么key:default对将被增加到map中
def myMap = [a:1, b:2, c:3] assert myMap['a'] == 1 assert myMap.a == 1 assert myMap.get('a') == 1 assert myMap['d'] == null assert myMap.d == null assert myMap.get('d') == null assert myMap.get('d', 0) == 0 assert myMap['d'] == 0 assert myMap.d == 0 myMap.d = 1 assert myMap['d'] == 1 myMap['d'] = 2 assert myMap.d == 2
keySet方法返回一个key的set集合,set是一个像list,但不包括重复的元素,并且集合中的元素没有固定的顺序;values方法返回map的值(value)的无序列表;entrySet方法可以将map转换为一个集合,这个方法返回一个实体的集合,在集合中的每一个实体都可以访问到key属性和value属性。
def myMap = [a:1, b:2, c:3] def map2 = [b:2, a:1, c:3] assert myMap == map2 assert myMap.isEmpty() == false assert myMap.containsKey('a') assert myMap.containsValue(1) assert myMap.keySet() == toSet(['a', 'b', 'c']) assert toSet(myMap.values()) == toSet([1, 2, 3]) assert myMap.entrySet() instanceof Collection assert myMap.any{entry -> entry.value > 2} myMap.every{entry -> entry.key < 'd'}