Map in groovy tutorial

This tutorial shows you various use of Map in Groovy.

Groovy has native language supports for java.util.Map, In addition Groovy has some Special syntax for map literals, and additional common methods. In this page we shows some additional common method of Groovy Map.

You can define an empty Map as

def map = [:]

and you can assign value as

You can use each() and eachWithIndex() to access keys and values:

		def str= new StringBuffer()
		map.each{ str << it.key +':'+ it.value +', '}
		println str.toString()

You can check the contents of a map with various methods:

		println [:].isEmpty()  // true
		println map.isEmpty()  // false
		println map.containsKey(2) // true
		println map.containsValue('b') // true
		println map.containsValue('z') // false

You can clear map as

		map.clear()
		println map

You can group a list into a map using some criteria:

		def map2 =[1:'a', 7:'b', 6:'b', 3:'c']
		println map2.groupBy{ it.key }
		println map2.groupBy{ it.value }

Above are some example on Groovy list.