Created
February 9, 2012 10:45
-
-
Save nicholashagen/1779211 to your computer and use it in GitHub Desktop.
Groovy Way to Convert List to Map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert any collection to a map by iterating over its contents | |
* and taking a result of the entry as the key to the map. The | |
* argument may either be a closure which is invoked once per item | |
* in the collection, or may be a string identifying the property | |
* to act as the key for each entry. | |
*/ | |
Collection.metaClass.asMap = { arg -> | |
def result = [:] | |
delegate.each { | |
if (arg instanceof Closure) { | |
def key = arg(it) | |
result[key] = it | |
} | |
else { | |
def key = it[arg] | |
result[key] = it | |
} | |
} | |
return result | |
} | |
/* TEST CASES */ | |
class Test { | |
def name; | |
def description; | |
} | |
def list = [ | |
new Test(name:'test1', description:'blah 1'), | |
new Test(name:'test2', description:'blah 2'), | |
new Test(name:'abc', description:'blah 3') | |
] | |
def test1 = list.asMap { it.name } | |
assert test1 instanceof Map | |
assert test1.containsKey('test1') && test1.containsKey('test2') && test1.containsKey('abc') | |
def test2 = list.asMap('name') | |
assert test2.instanceof Map | |
assert test2.containsKey('test1') && test2.containsKey('test2') && test2.containsKey('abc') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment