Details
-
Type:
New Feature
-
Status:
Closed
-
Priority:
Minor
-
Resolution: Fixed
-
Affects Version/s: 1.5.4
-
Component/s: groovy-jdk
-
Labels:None
-
Number of attachments :
Description
I've frequently run across the situation where I want to create a map from two equal sized lists, using one list for the keys and a second list for the values.
Maybe I'm missing something, but I can't seem to find a compact way to do this that doesn't require a for loop or an intermediate variable. The best I've come up with is to add this method to Map:
Map.metaClass.putEach = { List keylist, List valuelist ->
assert keylist.size == valuelist.size
for (int i=0; i < keylist.size; i++)
delegate
}
This allows you to just call putEach on any Map passing in two equal sized lists, e.g.:
assert [:].putEach(['key1', 'key2', 'key3'], ['value1', 'value2', 'value3']) == ['key1':'value1', 'key2':'value2', 'key3':'value3']
Since this seems generally useful, it might be something worth adding to the base GDK.
Just a note, I've also written another version that doesn't require the lists to be the same size.
Map.metaClass.putEach = { List keylist, List valuelist ->
{ def key = (keylist.size > i) ? keylist[i] : null def value = (valuelist.size > i) ? valuelist[i] : null delegate.put(key, value) }int count = Math.max(keylist.size, valuelist.size)
for (int i=0; i < count; i++)
delegate
}
This version is more flexible, but it can cause surprising results, e.g. this situation where the keylist is shorter than the valuelist:
assert [:].putEach(['key1'], ['value1', 'value2', 'value3']) == ['key1':'value1', (null):'value3']
I'm not sure which version you would consider to be more in the spirit of Groovy's JDK, but wanted to mention this second version.