alphanumeric
alphanumeric

Reputation: 19329

How to create map elements or dictionary from a list in Groovy

I have a list of elements in Groovy script:

my_list = ['key_1', 'value_1', 'key_2', 'value_2']

I want to turn this list to a Groovy map of elements (aka dictionary aka hash aka associative array) so it would look like:

[key_1: 'value_1', key_2: 'value_2']

How would you do it?

Upvotes: 1

Views: 3180

Answers (2)

tim_yates
tim_yates

Reputation: 171054

A much shorter method is:

def ​my_list = ['key_1', 'value_1', 'key_2', 'value_2']
​
def my_map = my_list.collate(2, false).collectEntries()
​
assert my_map == ['key_1':'value_1', 'key_2':'value_2']

Upvotes: 3

ou_ryperd
ou_ryperd

Reputation: 2133

This will work, depending on the reliability of the order in your list:

my_list = ['key_1', 'value_1', 'key_2', 'value_2']

my_map = [:]

my_list.eachWithIndex { item, idx ->
    if (idx % 2 == 0) {
        my_map[my_list[idx]] = my_list[idx+1]
    }
}

assert my_map == ['key_1':'value_1', 'key_2':'value_2']

Upvotes: 0

Related Questions