Basel Shishani
Basel Shishani

Reputation: 8187

Collect a list of pairs into a map

How can we collect a list of lists of value pairs into a map where said pairs are transformed into key:value entries in the map, as in:

a = [[1,11], [2,22], [3,33]]
b = ...?
assert b == [1:11, 2:22, 3:33]

Upvotes: 2

Views: 3497

Answers (3)

Will
Will

Reputation: 14539

Use collectEntries, which turns Iterables (like Lists) into Maps:

a = [[1,11], [2,22], [3,33]]
b = a.collectEntries { [ (it.first()) : it.last() ] }
assert b == [1:11, 2:22, 3:33]

Upvotes: 2

tim_yates
tim_yates

Reputation: 171144

Because collectEntries works with a pair list, you can just do

def b = a.collectEntries()

Upvotes: 5

AdamSkywalker
AdamSkywalker

Reputation: 11619

def b = a.collectEntries {[(it.get(0)): it.get(1)]}

Upvotes: 3

Related Questions