I'd like some sorthand for this:
Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
given the way the GDK stuff is, I'd expect to be able to do something like:
Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?
I can't find anything built in... but using the ExpandoMetaClass I can do this:
this adds the collectMap method to all ArrayLists... I'm not sure why adding it to List or Collection didn't work.. I guess that's for another question... but now I can do this...
from List to calculated Map with one closure... exactly what I was looking for.
Edit: the reason I couldn't add the method to the interfaces List and Collection was because I did not do this:
after that method call, you can add methods to interfaces.. which in this case means my collectMap method will work on ranges like this:
which yields the map: [0:0, 1:2, 2:4]
I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method
collectEntries
didn't exist yet. It works exactly as thecollectMap
method that was proposed:If for some reason you are stuck with an older Groovy version, the
inject
method can also be used (as proposed here). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!):The
+
operator can also be used instead of the<<
.Check out "inject". Real functional programming wonks call it "fold".
And, while you're at it, you probably want to define methods as Categories instead of right on the metaClass. That way, you can define it once for all Collections:
Example usage:
Was the groupBy method not available when this question was asked?
What about something like this?
Also, if you're use google collections (http://code.google.com/p/google-collections/), you can do something like this: