Monday, April 07, 2008

Firing My Own Volley

dangertree techblog has a series entitled "Groovy vs. Google Collections". In Round #1, chief provocateur Matt Taylor sent a devastating salvo of Groovy goodness in my general direction. The problem was to create combinations (dancing pairs) of girls and boys, and then group the dancers by boy and later by girl. I was able to meet the challenge with the help of Multimaps.inverseHashMultimap. I got "thumped" on code size however 37 to 12.

Matt has invited me to initiate Round 2, so now it's my turn.

Let's use a Multimap to associate the makes and models:
Multimap<Make, Model> makeToModel = Multimaps.newHashMultimap();
makeToModel.put(Ford, Taurus);
makeToModel.put(Ford, Focus);
makeToModel.put(Ford, Mustang);
makeToModel.put(Chevrolet, Malibu);
makeToModel.put(Chevrolet, Impala);
makeToModel.put(Chevrolet, Corvette);
makeToModel.put(Dodge, Charger);
makeToModel.put(Dodge, Avenger);
makeToModel.put(Dodge, Viper);
We can look up which models are built by a given make:
Make searchMake = Dodge;
System.out.printf("%s makes ", searchMake);
for (Model model : makeToModel.get(searchMake)) {
System.out.printf("%s,", model);
}
System.out.printf("\n");
The output is: "Dodge makes Viper,Avenger,Charger,"

We can now invert the map:
Multimap<Model, Make> modelToMake = Multimaps.inverseHashMultimap(makeToModel);
And this allows us to do a "reverse" lookup of make by a given model:
Model searchModel = Impala;
System.out.printf("model %s is made by %s\n", searchModel, modelToMake.get(searchModel));
The output is: "model Impala is made by [Chevrolet]"

Note that Make and Model are defined as enumerations. In this way, we can clearly see the difference in expected content between the forward (makeToModel) and inverse (modelToMake) Multimaps. Indeed, the Java compiler will complain if we attempt to put anything other than a Make/Model pair into makeToModel or if we attempt to get() from modelToMake with anything other than a Model.

The complete code is available on Pastie.

3 Comments:

At 5:14 AM , Blogger rhyolight said...

Here is my response. Cheers!

 
At 12:46 PM , Blogger Mario said...

This post has been removed by the author.

 
At 12:48 PM , Blogger Mario said...

This was fun.

--Mario

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home