2

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]
Basel Shishani
  • 7,735
  • 6
  • 50
  • 67

3 Answers3

5

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

def b = a.collectEntries()
Will
  • 14,348
  • 1
  • 42
  • 44
tim_yates
  • 167,322
  • 27
  • 342
  • 338
3
def b = a.collectEntries {[(it.get(0)): it.get(1)]}
AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
  • Thanks. You know, the confusing part for me is the requirement of the pair of parentheses around the first element - or just the break down of the syntax. – Basel Shishani Jan 20 '16 at 12:01
  • @BaselShishani yes, they look unusual, especially for java programmers – AdamSkywalker Jan 20 '16 at 12:08
  • 1
    @BaselShishani they are needed because the keys in maps are used as literal strings. `[ it : 90 ]` creates a map with a key `"it"`, whereas `[ (it) : 90 ]` creates a map with the key being the value in the `it` var – Will Jan 20 '16 at 12:11
2

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]
Will
  • 14,348
  • 1
  • 42
  • 44