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();We can look up which models are built by a given make:
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);
Make searchMake = Dodge;The output is: "Dodge makes Viper,Avenger,Charger,"
System.out.printf("%s makes ", searchMake);
for (Model model : makeToModel.get(searchMake)) {
System.out.printf("%s,", model);
}
System.out.printf("\n");
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;The output is: "model Impala is made by [Chevrolet]"
System.out.printf("model %s is made by %s\n", searchModel, modelToMake.get(searchModel));
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:
Here is my response. Cheers!
This post has been removed by the author.
This was fun.
--Mario
Post a Comment
Subscribe to Post Comments [Atom]
<< Home