Groovy vs. Google Collections, Round 1
In response to my comment, Matt Taylor challenged me to a "code-off" between Groovy and Google Collections.
Here is my response to his first challenge.
1. Create a set of boys and girls.
Set<String> boys = Sets.newHashSet("Paco", "Sven", "Roger", "Emelio");
Set<String> girls = Sets.newHashSet("Julia", "Prudence", "Lucy");
2. Discover every combination of them.Multimap<String, String> pairs = combinations(boys, girls);3. Group the combinations by boy and girl.
static Multimap<String, String> combinations(
Set<String> set1, Set<String> set2) {
Multimap<String, String> ret = Multimaps.newHashMultimap();
for (String s1 : set1) {
for (String s2 : set2) {
ret.put(s1, s2);
}
}
return ret;
}
for (String boy : boys) {
for (String partner : pairs.get(boy)) {
...
}
}
Multimap<String,String> pairsInverse = Multimaps.inverseHashMultimap(pairs);
for (String girl : girls) {
for (String partner : pairsInverse.get(girl)) {
...
}
}
Here is the full source code of the Google Collections version, courtesy Pastie.
Google Collections doesn't provide a combinations function like Groovy does. It would be nice to have the methods combinations(Set<T> ...) and permutations(Set<T> ...) in the Sets utility class.


6 Comments:
My only comment is this:
Google Collections: 57 lines of code
Groovy: 5 lines of code
For an improved comparison of the number of lines of code, Matt made a version of his Groovy script with formatting:
http://pastie.caboo.se/175750
and I made a version of the Java program without blank lines or comments:
http://pastie.caboo.se/175749
The brevity battle narrows to 37 lines of Java to 12 lines of Groovy.
Much of this disparity (9 lines of Java) is due to the fact that neither Java nor Google Collections includes an equivalent to the Groovy combinations function.
BOOYAH!!!
Now come back to the code in 8 months, introduce a typing bug, and see who catches it first.
Re: "Now come back to the code in 8 months, introduce a typing bug, and see who catches it first."
I guess you would expect that static typing would help catch errors more easily. Then again, with more code (including more boiler plate code) in the static version of the code, there is more scope for creating such errors.
And the winner is Groovy!! :)
Now it's time to do a benchmark
Post a Comment
Subscribe to Post Comments [Atom]
<< Home