Saturday, April 05, 2008

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);

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;
}

3. Group the combinations by boy and girl.
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:

rhyolight said...

My only comment is this:

Google Collections: 57 lines of code
Groovy: 5 lines of code

Dan Lewis said...

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.

rhyolight said...

BOOYAH!!!

Robert Fischer said...

Now come back to the code in 8 months, introduce a typing bug, and see who catches it first.

paulk said...

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.

Tiago Albineli Motta said...

And the winner is Groovy!! :)
Now it's time to do a benchmark

Subscribe to: Post Comments (Atom)


You are viewing a mobilized version of this site...
View original page here

Mobilized by Mowser Mowser