Thursday, 8 September 2011

BiMaps

Guava part 1 - MultiMaps

Next up on my tour of Guava, is the BiMap, another useful collection type. It's pretty simple really, a BiMap is simply a two way map.

Inverting a Map

A normal java map is a set of keys and values, and you can look up values by key, very useful, eg lets say I wanted to create a (very rudimentary) British English to American English dictionary:
Map<String,String> britishToAmerican = Maps.newHashMap();
britishToAmerican.put("aubergine","egglant");
britishToAmerican.put("courgette","zucchini");
britishToAmerican.put("jam","jelly");
But what if you want an American to British dictionary? Well you could write some code to invert the map:
    // Generic method to reverse map.
    public %lt;S,T> Map<T,S> getInverseMap(Map<S,T> map) {
  Map<T,S> inverseMap = new HashMap<T,S>();
  for(Entry<S,T> entry: map.entrySet()) {
   inverseMap.put(entry.getValue(), entry.getKey());
  }
  return inverseMap;
 }
It'll do the job, but there's several complications you might need to think about.
  • How do we handle duplicate values in the original map? At the moment they'll be silently overwritten in the reverse map.
  • What if we want to put a new entry in the reversed map? We'd also have to update the original map! This could get annoying.

BiMaps

Well, guess what? This is the sort of situation a BiMap is designed for! And here's how you might use it.

BiMap<String,String> britishToAmerican = HashBiMap.create();

// Initialise and use just like a normal map
britishToAmerican.put("aubergine","egglant");
britishToAmerican.put("courgette","zucchini");
britishToAmerican.put("jam","jelly");

System.out.println(britishToAmerican.get("aubergine")); // eggplant

BiMap<String,String> americanToBritish = britishToAmerican.inverse();

System.out.println(americanToBritish.get("eggplant")); // aubergine
System.out.println(americanToBritish.get("zucchini")); // courgette
Pretty simple really, but there's a few things to notice.

Enforcing uniqueness

Firstly the BiMap enforces uniqueness of it's values, and will give you an illegal argument exception if you try to insert a duplicate value, ie
britishToAmerican.put("pudding","dessert");
britishToAmerican.put("sweet","dessert"); // IllegalArgumentException.
If you need to add a values that has already been added there's a forcePut method that will overwrite the entry with the duplicate value.
britishToAmerican.put("pudding","dessert");
britishToAmerican.forcePut("sweet","dessert");  // Overwrites the previous entry
System.out.println(britishToAmerican.get("sweet")); // dessert
System.out.println(britishToAmerican.get("pudding")); // null

The inverse method

The other crucial thing to understand is the inverse method, this returns the inverse BiMap, ie the a map with the keys and values switched round.

Now this inverse map, isn't just a new map, such as my earlier reverseMap method might have created. It's actually a view of the of the original map. This means that any subsequent changes to the inverse method will affect the original map!
americanToBritish.put("potato chips","crisps");
System.out.println(britishToAmerican.containsKey("crisps")); // true
System.out.println(britishToAmerican.get("crisps")); // potato chips

So that's the BiMap, like I said pretty simple. As usual there are several implementations available, and as ever I recommend taking a look at the full API documentation: http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/collect/BiMap.html

Next up, Multisets!

Guava part 3 - Multisets

24 comments:

Sebastian Kusnier said...

You have a typo in your samples:
egglant -> eggplant

vatsal mevada said...

Quite helpful ...

Anthony Fedor said...

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

essay writing service reviews

arpan agrawal said...

Quite useful ..Thanks !!

My Assignment Help UK said...

I enjoy reading your blog. Thanks for update.
Need thesis help at BEST PRICE! Expert writers at MAH are ready to help you by providing top-notch thesis help to those students who want to make their future bright.Contact us now!

Ava Lee said...

Informative write up. When the pressure of producing an elaborate essay paper on a complex topic gives you sleepless nights, that’s when you should reach out to our best essay typer for essay help. These writers guarantee that the services provided by them are nothing short of excellent.

Juliet Morgan said...

Great post on the topic BiMaps.discount codes UK very much impressed by your way of writing.

Brinto said...

Good informative post.Alzheimers Care Tampa really enjoyed this reading.

Parks Rosa said...

It is good to read such a valuable information and thanks for sharing it. Livewebtutors is striving towards creating a great learning platform and hence, provide authentic Assignment Help to make it more informative.

Needcdrreport said...

I am happy to find this blog very useful for me. As it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing. We also provide CDR Report .

onlinecontentwritinghelp said...

You have posted a piece of information which I was searching for a long time. Thanks for helping us to improve our knowledge by your precious information. write my essay

Ireland Assignment Help said...

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. assignment helper

Singapore Assignment Help said...

We offer free dissertation help singapore services by Excellent Dissertation Writers from Top Global Universities.

mycoursehelp said...

Thank you for posting such a great blog! I found your website perfect for my needs. It contains wonderful and helpful posts. Keep up the good work. Thank you for this wonderful Blog!
Visit: Homework Help

MyAssignmentHelpSG said...

An unmatched and nonpareil post i have ever seen. The content is so appealing that it has created an impulse to avail Assignment Help Singapore services.

RItuparna Das said...

Keep posting in same way really appreciate the efforts you put in writing waiting for next edition
Delhi Escorts Booking
Escorts Kolkata
Goa call girls Services
Sexiest escorts in Delhi

prashant said...

matlab assignment help

Online Assignmet Help said...

Excellent information on your blog, thank you for taking the time to share with us. Amazing insight you have on this, it's nice to find a website the details so much information about different artists.
visit here:- nursing assignment help

Mike Rock said...

best site for the student to get help in their studies and assignments Get Help in Comparative Analysis Assignment

Mike Rock said...

glad to be here Returner 77 on PC

Mike Rock said...

thanks for it mail.com mail

Mike Rock said...

so amazing Fly

Mike Rock said...

such a nice post Bricks Breaker

Mike Rock said...

glad to be here Droid VPN for PC and Laptop