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")); // courgettePretty 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:
You have a typo in your samples:
egglant -> eggplant
Quite helpful ...
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
Quite useful ..Thanks !!
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!
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.
Great post on the topic BiMaps.discount codes UK very much impressed by your way of writing.
Good informative post.Alzheimers Care Tampa really enjoyed this reading.
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
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
We offer free dissertation help singapore services by Excellent Dissertation Writers from Top Global Universities.
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
best site for the student to get help in their studies and assignments Get Help in Comparative Analysis Assignment
glad to be here Returner 77 on PC
thanks for it mail.com mail
such a nice post Bricks Breaker
best site ever Island Survival For PC
so amazing Duck Warfare for PC
i found it so amazing Fix black screen
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.
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.
This is very nice one and gives indepth information. Thanks for this nice article A Report On Business Environment: The Heathrow Airport
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.
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.
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.
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).
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.
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.
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.
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.
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
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.
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.
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
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/
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
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.
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
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
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
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.
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
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
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.
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.
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.
gomt in nagar escorts independend
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
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
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.
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
Hamd Technologies providing you the best Customer Relationship Management Software Zoho CRM.
Zoho CRM
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.
His estimated net worth is around a whopping $7 billion, as of March 2021 according to our news reports.
Mitchell Rales net Worth
He is an American professional wrestler, better known by the ring name Ricochet. He is currently signed to WWE.
Ricochet Information
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
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.
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.
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
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.
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.
Great articleessay typer Ottawa
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
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.
nice blog you have here, you can check national common entrance past questions download
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.
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.
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!
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.
"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."
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.
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.
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.
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.
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!
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
Tom's Programming Blog on BiMaps offers valuable insights into efficient data handling and algorithm optimization, making it a useful resource for programmers. The discussion around BiMaps emphasizes their practical application in managing bidirectional relationships within data structures. For those who want to stay comfortable while coding or attending tech events, oversized hoodies for men featuring tech-inspired designs would make a perfect addition to their wardrobe. This blend of functionality and comfort adds to the overall tech experience!
Post a Comment