Search

Dark theme | Light theme

January 4, 2010

Groovy Goodness: Turn a List into a Map

With Groovy we can use the values of an Object array and transform them to a map with the toSpreadMap() method. The array must have an even number of elements, because the odd elements are the keys for the new map and the even numbers are the values for the keys. The SpreadMap object, which now contains the keys and values, is an immutable map, so we cannot change the contents once we have created the map.

def list = ['key', 'value', 'name', 'mrhaki'] as Object[]
def map = list.toSpreadMap()

assert 2 == map.size()
assert 'value' == map.key
assert 'mrhaki' == map['name']