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

82 comments:

Unknown said...

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

vatsal said...

Quite helpful ...

Unknown 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 !!

Anonymous 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.

Unknown 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.

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.

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

mikerock said...

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

mikerock said...

glad to be here Returner 77 on PC

mikerock said...

thanks for it mail.com mail

mikerock said...

such a nice post Bricks Breaker

mikerock said...

best site ever Island Survival For PC

mikerock said...

so amazing Duck Warfare for PC

mikerock said...

i found it so amazing Fix black screen

Unknown said...

Thank you for this breathtaking article and I like this. It is good to read such valuable information and thanks for sharing it. Here, you can check your love tarot card reading for singles here.

Anonymous said...

Incredible post. This article is exceptionally useful for the general population and furthermore for me.
I get the some helpful information in this post. A debt of gratitude is in order for sharing the instructive point.
I found one blog on How to secure your teen from digital technology.

Alley John said...


This is very nice one and gives indepth information. Thanks for this nice article A Report On Business Environment: The Heathrow Airport

John Bravo said...


I think your advice will be helpful for me. I will inform you
thanks admin of this website.
Read about Bit Guardian Parental Control App how it is helpful to secure your kids.

Ricky Hardy said...

MyAssignmenthelp.com keeps a careful check on each review that is posted in the site. If any myassignmenthelp fake review is posted, it is immediately removed by the administrative department. Therefore, the student’s words are enough to prove that MyAssignmenthelp.com is a reliable assignment service provider.

Alley Walker said...
This comment has been removed by the author.
Alley Walker said...
This comment has been removed by the author.
watson769 said...

A term of the contract is a provision that forms part of a poussard v spiers. Every term in a contract creates a contractual obligation which when breached by either of the parties leads to litigation for the breach. All the terms of a contract are not expressly stated in the contract.

peck38 said...

Starbucks Marketing Plan believes that with targeting of high end coffee drinker along with coffee creamer, as consistent with present practices. The Corporation aims at achieving new segment of coffee drinkers. The report aims at developing a marketing plan for Starbucks (Lapersonne, 2013).

Suhana Williams said...

If you ask what are the qualities that distinguish Assignmenthelp.us from rest of the online essay help services in USA, here goes the reason. We can guarantee that no other online essay help service is as meticulous as we are when it comes to guiding students with bibliography, referencing and citation problems. Along with helping students with essay writing, we simultaneously take care of the post-writing stages. Need Pay someone to buy an essay? Learn the details of referencing, in-text citation, different referencing styles and many more only from us.

rich38 said...

Oligopoly characteristics is an important market type in which there are few firms that accounts for producing and selling a product. In simple words, it can be best described as a market situation which explains competition between the two.

watson769 said...

A term of the contract is a provision that forms part of poussard v spiers. Every term in a contract creates a contractual obligation which when breached by either of the parties leads to litigation for the breach. All the terms of a contract are not expressly stated in the contract.

watson769 said...

A term of the contract is a provision that forms part of poussard v spiers. Every term in a contract creates a contractual obligation which when breached by either of the parties leads to litigation for the breach. All the terms of a contract are not expressly stated in the contract.

Ideal Assignment Help said...
This comment has been removed by the author.
anurag said...

SSC CGL Tier 2 admit card 2018-19 will be available here. After successful completion of tier 1, aspirants are waiting for the declaration of result of tier 1 and Admit card for SSC CGL tier 2 examination.

Unknown said...

AppSquadz is globally acknowledged as the top mobile app development company with 100% satisfied customers. We contribute the best to our customers to maintain a dynamic market. For further information visit our website: https://www.appsquadz.com

Bill Caster said...

Key to get quick assignment help The process of assignment writing involves many stages. You have to apply your time management strategies in each of these stages to submit a paper that will definitely score good grades.

Myassignmenthelp.com said...

Thank you for sharing this informative post.MyAssignmenthelp.com is giving dissertation conclusion help to students.we are already trusted by thousands of students who struggle to write their academic papers and also by those students who simply want how to structure a dissertation to save their time and make life easy.

Koka Queen said...

Thanks for Your article..it gives us immense knowledge. Body massage gives you ultimate relief to your body.I would like to recommend each and everyone go for massage once in a week for ultimate relief. it will not only gives you relief but also increase your productivity.

call girls in Jaipur

Escort services in Jaipur

College Call girls in Jaipur

High class Call girls in Jaipur

House Wife Escort services in Jaipur

Desi call girls in Jaipur

VIP Escorts services in Jaipur

VIP Call girls services in Jaipur

Body Massage in Jaipur

Sandwich Massage in Jaipur

William smith said...

Assignmenthelp.net is the best online assignment help website providing affordable and reliable quality assignment help.Want an early Christmas gift? Hurry up grab your offers and discounts today. Limited time offer.https://www.myassignmenthelp.net/

Ashley said...

This post really help me when I was in trouble in my Assignment Help. Thanks for sharing such an informative blog, be continue to write such amazing information. Who can write my essay online?

Biology assignment help
Computer Science Assignment help
Mathematics assignment help
Law Assignment help
Economics Assignment help

James Abe said...

Great Post!
If you are looking for an assignment help, you have come to the right place. Assignmenthelpaus.com offers huge amount of papers and essays. We provide the Academic Assignment Help work according to their writing style. You will get the unique Assignment Writing Services from us.

Seohunter said...

About Us support.themely
About Us support.themely
About Us support.themely
About Us support.themely
About Us support.themely
About Us support.themely


thanks For UR article

William Smith said...
This comment has been removed by the author.
buy logo custom said...

This is a very fantastic and helpful information post..
Thanks for sharing with us,
We are again come on your website,
Thanks and good day,
If you need any logo then,
Please visit our site,
buylogo

assignmentauthors said...

Equality and diversity is another virtue. Police are to ensure that all people are equal before the law and also the police are not above it and safeguard human rights. ebook writing service

Monnika Jacob said...

I use the Guava library in practically every Java project I create. If you feel any trouble, visit cheap dissertation writing services and I'll show you how to find Guava.

Alley John said...

If you are searching for instant assignment help service then you don’t need to go anywhere, you can get all the answers of your queries over on My Assignment Help

Jordan said...

Excellent blog here! It’s incredible posting with the verified and truly helpful information…...Most beautiful places in the world  | bordeaux France  | things to do in bordeaux | beautiful places in Pakistan | Bali Indonesia | Explore Worldwide | lake Tahoe attractions | Kumrat Valley



Globex Writing Services said...

Hey, Informative Post. Thanks for sharing keep writing these type of articles and help people to get more knowledge.Check out an other informative guide about website content writing services. I assure this content will prove useful in making your work more attractive and persuasive.

Alley John said...


Word Counter Tool is a free online word count tool to help you count and calculate the number of words in a text. This online tool can also calculate the total character or letter count, sentences, and paragraphs for the text entered in the input box. So connect with MyAssignmentHelp for getting the best Word Counter.

Keith Morris said...

With the best in class turnaround time and also avail amazing value-added service, And Get in touch with the Best Programming Assignment Help who are very talented in providing solutions on various topics on subjects. You Read it Right! We are here to help you with your queries on your assignments. We are providing you with a world-class and Highly Talented Assignment expert. These Assignment Writers who are capable of doing any writing services, and many other writing services such as Assignment Writing Services, Assignment Help for various subjects such as Engineering Assignment, Statistics for the students across Australia, and also for students across UK, USA, Malaysia and various other countries.

Vikash said...

gomt in nagar escorts independend

investmango said...

Excellent information Providing by your Article, thank you for taking the time to share with us such a nice article. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. Investmango goal is to offer unique and specialized services to our clients and in return create a long-lasting working relationship. We provide the Best Godrej 43 Noida and 2/3/4 BHK Flats, Apartments, Penthouse, Corporate Properties, Commercial Properties in Noida, Greater Noida West, Delhi NCR with Great Discount and Deals. Learn more about the Investmango visit our website and call now :- +918076042671

AL FAHAD IT CONSULTING said...

The blog is very informative, and I take lots of help from this blog, thanks for sharing.

Our vision is to inspire people to challenge their goals and enhance their productivity with effective and reliable Information Technology Solutions. We organize high-caliber IT Solutions that maximize your business and increase your business infrastructure. Enlightened your interaction with our cloud-based IT Solution services and make your business more productive efficiently.



Furniture Inventory Software

Eva Wilson said...

We assign you the best academic online dissertation proposal as per your project requirement, Order your dissertations and have one of the best custom dissertation help. We have experienced dissertation writers from every field.

Eva Wilson said...
This comment has been removed by the author.
Eva Wilson said...

Superb i really enjoyed very much with this article here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.


Regards,
Online Thesis Help

Tamika baden said...

Hamd Technologies providing you the best Customer Relationship Management Software Zoho CRM.

Zoho CRM

William smith said...

My Assignment Help is an acclaimed site that provides the best online university online Finance Assignment Help by top native financial assignment writers. Our experts are ready to lend their hand and help you learn the concepts. Order now to get the best assignment help from the experts.

hassam said...


His estimated net worth is around a whopping $7 billion, as of March 2021 according to our news reports.
Mitchell Rales net Worth

H said...

He is an American professional wrestler, better known by the ring name Ricochet. He is currently signed to WWE.
Ricochet Information

Faraji Sibongile said...

I read your blog and i found it very interesting and useful blog for me. I hope you will post more like this, i am very thankful to you for these type of post.
ecelebrithytrend.com Bailey Sarian net worth

Max Russell said...

I would like to thank you for the efforts you have made in writing this post. Thanks for posting Such Things. I should recommend your site to my friends. If you are interested in Android app development companies USA.

William smith said...

Want Statistics Assignment Help Online? Let Our experts Help you. Choose My Assignment Help to get quality assignment help. Avail the unmatched assignment help service that deliver unique, on-time and high-quality assignment.

Ankit Ron said...

I just played Carrom Online game on the website fantasy power 11. I got real money in my paytm wallet. Thank you for this wonderful game share and excellent information providing by your article

Assignment Help Pro said...

With the help of the Online assignment helpers, you can have the best academic writing agency create your valuable answer. If you are seeking assignment help, you should consult a professional instead of going from place to place. Throughout Australia, we provide assignment assistance. We provide quality solutions for this purpose.

Anonymous said...

Nice job. On the other side, if anyone looking for write that essay then visit at sourceessay.com as soon as possible to solve entire assignment writing dilemma.

Anonymous said...

Great articleessay typer Ottawa

Hope James said...

Acadecraft is a top-tier content development and elearning services company. It also delivers renowned scenario based learning.
The company is known for accurate, authentic, and affordable content. For further queries, drop a mail at info@acadecraft.com.

Also Read: e authoring tools

Sample Assignment said...

sampleassignment.com is Australia's leading Academic writing service. We offer a wide range of writing services including Assignment Writing, Essay Writing, Dissertation Writing and Coursework Writing. We have a team of qualified writers who can cater to your needs. Whether you need help with a school assignment or you're studying abroad, we are here to make your academic life easier. get Australia Assignment Help with our experts.

EIbass said...

nice blog you have here, you can check national common entrance past questions download

Unknown said...

Dear Tom, as a family doctor, I appreciate your programming blog as it highlights the importance of technology in healthcare. I would also like to share that Meri Sehat.pk offers online healthcare services, making it easier for patients to connect with doctors anytime, anywhere. Keep up the good work and let's continue to bridge the gap between healthcare and technology.

Steven Smith said...

These services are available for a wide range of subjects and levels, from high school to college and beyond. When students seek online assignment help, they can expect assistance with various types of assignments, such as essays, research papers, lab reports, presentations, and more.

Blogs said...

I highly recommend Assignment Help Pro for Nursing Assignment Helper. Their expert team delivers top-notch assistance, ensuring comprehensive and well-researched assignments. With their support, I've achieved excellent grades and gained a better understanding of nursing concepts. Give them a try; you won't be disappointed!


nancysweety said...

It might be easier for your man to enjoy female to male massage in pune an orgasm from prostate stimulation if you’re the one doing the work and he can simply focus on the sensation.

Blogs said...

"I found this post insightful and informative. When it comes to assignments, I always rely on Assignment Help Online from Do My Assignment. Their assistance has been invaluable, ensuring my academic success. I highly recommend their services."




Blogs said...

I appreciate this informative blog post. Nursing is a demanding field, and Assignment Help Pro's online assistance can be a valuable resource for nursing students seeking guidance and support with their Nursing Assignment Help Online. Their expertise can make a real difference in academic success.

Blogs said...

I appreciate the insightful content shared in this post. When it comes to academic support, Do My Assignment offers excellent Assignment Help Online services. Their expertise ensures top-notch assistance for students.




Blogs said...

I appreciate the insightful content on this blog post. For additional assistance with academic tasks, consider seeking Assessment Help Online from Do My Assignment. Their expertise ensures quality results, enhancing your academic journey.





online tuition classes said...

Discover a world of opportunities with our guide on Career Options After 12th Commerce. This comprehensive resource explores the diverse paths available to students after completing their 12th grade in the commerce stream. From traditional roles in accounting and finance to innovative careers in digital marketing and entrepreneurship, our guide on Career Options After 12th Commerce provides insights into various fields, helping students make informed decisions about their future careers.

SSSi said...

Kudos to you for researching so much about the maths online tuition. Your blog is very helpful for the students and their parents. This blog can help young students to search for the proper guidance. I would love to see more blogs like this from you in the near future. Keep writing more blogs like this!

flip bodyspa said...

Our b2b spa in chennai provide best services may include Botox injections, laser treatments, chemical peels, and other cosmetic procedures and also provide best hot massage girl therapists