In my last post, Dan Lewis (my friend and former coworker) responded with some counter-code from Google’s collections package. Instead of attempting to snap back with some witty technical retort, I challenged Dan to a code-off. Groovy collections vs. Google collections (in Java). Here is round one, and I’m going first with an example of finding combinations of collections. Hopefully, you can soon find Dan’s response in Google collection code-style on his blog.
def boys = ['Paco', 'Sven', 'Roger', 'Emelio']
def girls = ['Julia', 'Prudence', 'Lucy']Now we have two simple lists, one of boys and one of girls. So what if these are all dancers, and we’d like to know all the combinations of dancers there could be? With groovy, this is extremely easy.
def combos = [boys, girls].combinations()Could it be any easier? This creates a list of lists, each inner list containing a possible combination:
Now it would be nice if i could split the list up in some way, maybe keying by male or female. Groovy’s groupBy collection method is an easy way to do this. In the closure you provide, you simple return the key that you want to group the collection by, and it will return a map with that key pointing to a list of values. In the following example, because I know the first element of each combination is the boy and the second is the girl, I just specify a key by element position.
def groupedByBoys = combos.groupBy { it[0] }
def groupedByGirls = combos.groupBy { it[1] }Which returns these two groupings:
Beat that, Google Collections!

5 Comments
I have posted a response.
In all fairness, the complete groovy code to print out the same as Dan’s is here, and it is 12 lines:
def boys = ['Paco', 'Sven', 'Roger', 'Emelio'] def girls = ['Julia', 'Prudence', 'Lucy'] def combos = [boys, girls].combinations() println combos def groupedByBoys = combos.groupBy { it[0] } def groupedByGirls = combos.groupBy { it[1] } groupedByBoys.each{ key, val -> println "Partners of ${key}: ${val.collect{ it[1] }}" } groupedByGirls.each{ key, val -> println "Partners of ${key}: ${val.collect{ it[0] }}" }This prints out the following:
This is awesome. I’m looking forward to round 2!
One more neat thing about combinations that I didn’t mention: You aren’t restricted to two lists to combine. It can be as many as you want:
def girls = ['Julia', 'Prudence', 'Lucy']
def locs = ['Milan', 'Prague', 'St. Louis', 'Toronto', 'Hong Kong', 'Los Angelos']
def combos = [boys, girls, locs].combinations()
produces:
It’s Beatifull!
2 Trackbacks
[...] dangertree techblog sweaty programming and disconnected gibberish « Groovy vs. Google Collections: Round #1 [...]
[...] vs Google Collections. Matt on Groovy. Dan on Google [...]