Thursday, 1 September 2011

Multimaps - Google Guava

Guava?

This is the first in a series of posts where I'll be attempting to explain and explore Google's awesome Guava java library.

I first came across Guava whilst searching for generic versions of Apache Commons Collections - I needed a Bimap and was fed up with having to pepper my code with casts - however what I found was much much better.

Not only does it contain various implementations of more complex (but useful) collection types - Multimaps, Multisets, Bimaps - which I'll discuss in detail, but also facilities to support a more functional style of programming with immutable collections, and function and predicate objects. This has both completely changed the way I write java, and at the same time made me increasingly frustrated with Java's sometimes clunky syntax, something I intend to explore in further posts.

Anyway enough with the introduction, and on with the good stuff. The first thing I'd like to take a look at is the Multimap, which is probably the single Guava feature I've made the most use of.

Mutlimaps

So, how often have you needed a data structure like the following?

Map<String,List<MyClass>> myClassListMap test2
                              = new HashMap<String,List<MyClass>>()


If you're anything like me, fairly frequently. And don't you find yourself writing the same boilerplate code over and over again?

To put a key/value pair into this map, you need to first check if a list already exists for your key, and if it doesn't create it. You'll end up writing something along the lines of the following:

void putMyObject(String key, Object value) {
    List<Object> myClassList = myClassListMap.get(key);
    if(myClassList == null) {
        myClassList = new ArrayList<object>();
        myClassListMap.put(key,myClassList);
    }
    myClassList.add(value);
}


Bit of a pain, and what if you need methods to check a value exists, or remove a value, or even iterate over the entire data structure. That can be quite a lot of code.

Never fear Guava is here!

Just like the standard java collections, Guava defines several interfaces and matching implementations. Usually you want to code to an interface, and only worry about the implementation when you create it. In this case we're interested in Multimaps.

So using a multimap, we could replace the data structure declaration with the following:

Multimap<String,Object> myMultimap = ArrayListMultimap.create();


There's a few things to note here. The generic type declaration should look very familiar, this is exactly how you would declare a normal Map.

You may have been expecting to see new ArrayListMultimap<String,Object>() on the right-hand side of the equals. Well, all Guava collection implementations offer a create method, which is usually more concise and has the advantage that you do not have to duplicate the generic type information.

Guava in fact adds similar functionality to the standard Java collections. For example, if you examine com.google.common.collect.Lists, you'll see static newArrayList(), and newLinkedList() methods, so you can take advantage of this conciseness even with the standard Java collections. (I'll aim to cover this in more detail in a future post).

So we've declared and instantiated a multimap, how do we go about using them? Easy just like a normal map!

public class MutliMapTest {
    public static void main(String... args) {
  Multimap<String, String> myMultimap = ArrayListMultimap.create();
  
  // Adding some key/value
  myMultimap.put("Fruits", "Bannana");
  myMultimap.put("Fruits", "Apple");
  myMultimap.put("Fruits", "Pear");
  myMultimap.put("Vegetables", "Carrot");
  
  // Getting the size
  int size = myMultimap.size();
  System.out.println(size);  // 4
  
  // Getting values
  Collection<string> fruits = myMultimap.get("Fruits");
  System.out.println(fruits); // [Bannana, Apple, Pear]
  
  Collection<string> vegetables = myMultimap.get("Vegetables");
  System.out.println(vegetables); // [Carrot]
  
  // Iterating over entire Mutlimap
  for(String value : myMultimap.values()) {
   System.out.println(value);
  }
  
  // Removing a single value
  myMultimap.remove("Fruits","Pear");
  System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]
  
  // Remove all values for a key
  myMultimap.removeAll("Fruits");
  System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
 }
}


One thing you may be wondering, is why does the get method return a Collection and not a List, that would be much more useful. Indeed it would. The problem is there are several different implementations available, some use Lists - ArrayListMultimap, LinkedListMultimap etc. - and some use Sets - HashMultimap, TreeMultimap among others.

To handle this - if you need to work directly with the Lists, or Sets in the map - there are several subinterfaces defined. ListMultimap, SetMultimap, and SortedSetMultimap. These all do what you'd expect, and their methods that return collections, will return one of the approprite type.

ie

ListMutlimap<String,String> myMutlimap = ArrayListMultimap.create();

List<string> myValues = myMutlimap.get("myKey");  // Returns a List, not a Collection.



That's basically all there is to them. I recommend looking at the API: http://docs.guava-libraries.googlecode.com/git-history/release09/javadoc/com/google/common/collect/Multimap.html, where you can find the various implementations, you should be able to find one that suits your needs.

So, that's all for now. In my next post, I'll be introducing the BiMap

Guava part 1 - MultiMaps
Guava part 2 - BiMaps
Guava part 3 - Multisets

84 comments:

Balaji said...

Hi

Cannot see any of your code. Could you please post them?

Bill said...

Java collections do not make very good first-class objects--they are more like intrinsic--ints, floats, strings--in that they do not actually indicate any specific business functionality.

I've come to believe that it's a really bad pattern to pass them between classes or--in general--use them outside a tight business class.

Encapsulation is necessary here, collections alone cannot be made "Safe" (Well, except immutable ones) and you cannot add methods to them, so they require "Utility" code to operate on them.

There are cases where mingling sets is highly desired, I don't find Java a very good syntax for these cases--Groovy is a good deal better.

Java and OO are much better at dealing with business solutions than utility-type solutions. I think that this is by design, I simply don't code some things in Java (Groovy is actually pretty good for many of them).

I tend to be one of the strongest Java proponents around, but how could anyone think that one language should fit every need you could possibly come up with?

Paweł Michalski said...

Hi, Your link to API has expired. Anyway, thanks for good article. :)

Mihai Ciobanu said...

After removing the pair {"Fruits", "Pear"}, you have [Banana, Apple] left, not [Banana, Pear]

chetanyn said...

Is there a way to get the key from the value in Multimaps?

uchiha manga said...




thank you first for the information but if
you want to loss weight fast read more information here

and for more information about Guava recipes

Pravanjan Niranjan said...

good one . Thanks

+918867188053 said...

Thank you somuch foor your for your good Article. i learned something new. Thanks once agian.

Kleber Vianna said...

you java examples in http://tomjefferys.blogspot.com.tr/2011/09/multimaps-google-guava.html on multimaps don't even compile.

Silvia Jacinto said...

Eating is really one of my hobby i mean part of my life and cooking is my passion. I also love going to a place and at the same time taste their delicious and most wanted food.I want to taste something that is new to my palate. Thanks for sharing your article with us.

n8fan.net

www.n8fan.net

Java Proficiency said...

visit guava tutorial with well explain examples

http://www.javaproficiency.com/2015/05/guava-tutorial-for-beginners.html

sarah lee said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


edupdf.org

qwe qweqwe said...

the 'www.chose1ofbest.blogspot.com' url points to 'http:://www.chose1ofbest.blogspot.com'. Sorry, was testing my crawler, and it causes HTTPerror... -_-...

addirigib said...

The blog is having enjoyed article and content is also having great and verity of information here. The best thesis writing is helps for college studies and research for making good and successful writing papers

Alex Milner said...

This is an absolutely amazing programming content. I never knew that I would come across such comprehensive and a well-explained computer knowledge. You have done a great work author. I am proud of you. Online editors can help you in Correcting Errors in a Personal Experience Essay on your technological experiences.

Neil Jakson said...

This blog seems seriously good. Thanks for providing all this information at no cost.
Dissertation writing services

Jessica Jeon said...

To have a better exposure to your facebook account, Individuals expend bucks to Buy Facebook Followers to very easily obtain exposure online. buy followers on facebook

manoj kumar said...

For getting a greater exposure for your facebook account, Individuals spend cash to Buy Facebook Followers to very easily find exposure online. get facebook followers

samia hussain said...

nice post

Creativeessay writing said...

This is very informative blog and very helpful. I got something new information about the google's guava library. This is new term for me and I read it seriously. Get more help from thesis writing service for your academic task.

Joseph said...

This is a very nice post and it is really helpful.Keep sharing as we get more information for how many written pages is 500 words within the given essay.

mayazoe said...

Pick a Topic - The first step in writing a research paper is picking a topic. Make sure that you pick a topic that is interesting to you, and has plenty of information available about it.
homework being banned

Steven Frayne said...

Many thanks for sharing this very diverse opinion post where each expert has no doubt shared his best knowledge on the topic. Have more success in your journey.
Online assignment Help Sydney

Tracy Johns said...

This blog seems seriously good. Thanks for providing all this information at no cost.

Send Flowers To Japan

My Assignment Help UK said...
This comment has been removed by the author.
amta khan said...

Wow! This is real good site for the readers as the content in this sites is very informative and it makes us pleasure to read the whole content. Send Gifts To pakistan

Linda Cochran said...

To find an increased exposure for your facebook account, Persons spend funds to Buy Facebook Followers to conveniently have exposure on internet. paid facebook followers

MaryWooten said...

Interesting blog. I am glad I found it.
Write my paper for cheap

Merin said...
This comment has been removed by the author.
Writer said...

Sometimes, it's more important to practice on programming tasks than write assignments. That's why students buy essays online.

Moshe Rabinovich said...

You made some decent factors there. I appeared on the web for the difficulty and found most individuals will go together with with your website. online casino gambling

Parks Rosa said...

Thanks for sharing this blog post which is very informative. I am working as an academic consultant in Australia and offer Excellent Assignment Help Services to college students.

xccc said...

Which are the indicators of global recognition of individuals during this contemporary world? Of course, amount of followers on the Twitter account can be described as firm indication in today. Buy Twitter Permanently followers

dipali sharma said...

It can serve as a fantastic advertising device that can serve as a magnetic to bring in the remarkable opportunities in terms of followers, clients, clients as well as various other networking probabilities. buy targeted facebook likes

Siena Williams said...
This comment has been removed by the author.
Gift cards said...

Hey friends try sudoku online its best way to play sudoku online for free.

Krystal Barnett said...

If you are being guaranteed 24/7 Support and lifetime replacement then don’t think again after you Buy facebook reviews from a service agency. buy facebook ratings

Natasha Kale said...

Have you been hunting for valid YouTube subscribers? Forget your fears, we shall diligently help you to buy YouTube subscribers. buying youtube subs

Unknown said...

An opportunity to read a fantastic and imaginary blogs.It gives me lots of pleasure and interest.Thanks for sharing. Here it is about Agriculture products. If you need to buy Best quality herbicides and other crop protection chemicals you also can go through these links.

Saadat Abbas said...

Very Interesting topic to read.Thanks For sharing it.
Send Gifts to Pakistan

Dylan Eales said...

Thanks for this informative content. It’s really good. Actually, I want to share some thoughts and reviews about an assignment help Australia company in Australia and the brand name is SAMPLE ASSIGNMENT. Here, I am working as an Academic Expert. To look at our online academic assistants who provide reference assignment including Accounting, Management, Finance, IT, Economics, Computer Science, Nursing, Marketing; all Academic subjects to University Students all over the Australia or even worldwide, Here is a big online assignment help providers who help students to get HD grades according to assessment guidelines and instructions. Those who are searching for assignment help Melbourne, Perth, Brisbane, Adelaide etc. get a touch with Sample Assignment - the No.1 Assignment provider. Any student really wants to buy an assignment at the cheapest price goes to our branded website and has a look and opts our amazing and informative services, you can avail of our convenient online assignment help and samples available on our website for free. You can download it if you want. Are you ready to get 100 out of 100 in your university assessment? We assign the best writer according to the subject for your academic problems and provide support in assignment writing services. Our Customer Care Executives are available 24*7 hours to assist you in the best possible manner. Phone calls and emails are the best methods used by online assignment maker.

Natasha Kale said...
This comment has been removed by the author.
Unknown said...

Thanks for sharing this information. We need such information to create CDR Reports. You can get complete CDR Report Writing Service from us. We also provide CDR Reports in Australia, Summary Statement Writing and Career Episode Writing.
Thanks for sharing this information. We need such information to create CDR Reports. You can get complete CDR Report Writing Service from us. We also provide CDR Reports in Australia, Summary Statement Writing and Career Episode Writing.

Saadat Abbas said...

Very Interesting topic to read.Thanks For sharing it.
Mother's Day Hampers UK

Unknown said...

Assignment Help Shop offer high-quality Assignment Writing Services in Australia at cheap rates.

Saadat Abbas said...

Eating fruit on a regular basis can boost health.
Father's Day Fruit Baskets

Saadat Abbas said...

The only thing better than an incredible gift is an incredible gift that's personalised.
Personalised Gift UK

المتألقون للصيانة والتشطيب وكشف تسريبات المياه said...

شركة مكافحة حشرات براس تنوره
شركة تسليك مجارى بعنك
شركة تسليك مجارى بسيهات
شركة تسليك مجارى براس تنوره

prashant said...

Are you in search of MATLAB Assignment Help or any assistance with MATLAB Project Help Services?? Nothing to worry when MATLAB Solutions team is here. Leave all your Matlab Programming problems on us.

prashant said...


I would like say thanks for this post. Here are some useful links for stdudents all across the globe. If you are looking for assignment help, we are the best providers for you. We have our services which include :
Python Assignment Help
Electrical Engineering Assignment Help
Programming Assignment Help

Assignment Help said...

Assignment Help Shop is the best place to buy paper online. We provide service of buying assignment help online of higher quality, without plagiarism.

Indonesian Courses said...

Panasonic
Samsung
Huawei
Service iPhone Lampung
iPhone
Vivo
Oppo
Xiaomi
Service HP Bandar Lampung

Sharp Indonesia said...

www.lampungservice.com
https://servicecentermito.blogspot.com/
https://youtubelampung.blogspot.com/
https://konsultanhp.wordpress.com/
https://komunitasyoutuberindonesia.wordpress.com
https://youtuberandroid.wordpress.com
https://youtuberterbaikindonesia.wordpress.com

Emma Jolie said...

Thanks for sharing this valuable information, I am here to share some benificial information for stduents looking for cdr report help. We are cdr report service providers providing , ka02 writing services, career episode writing and rpl report writing.

John Oneal said...

Avast Customer Service
Norton Customer Service
Bitdefender Phone Number
McAfee Customer Service Number

prashant said...


Here I am sharing a very useful resource for students looking for assignment help. ProAssignmentHelp providing all sort of assignment writing in various subjects like as : Electrical engineering assignment help , electronics assignment help , MATLAB assignment help , management assignment help , etc.

abcassignmenthelp said...

ABC Assignment Help is an incomparable online Engineering assignment help company delivering excellent academic assignments, essays, coursework and reports. Through a team of over 3000 subject experts we ensure individual attention to every student making the assignment help experience completely personalized in nature.

rickypauls said...

So far, I found this website very professional for assignment writing. I took Assignment Help from them for my Science homework. I am really happy with the experience and I will recommend this website to you guys if you need quality writing services for your project.
I had to complete my English assignment and I was worried because my assignment was not ready. I took the help from google but still fail to write. Then, I took Assignment Help Online from greatassignmenthelp and I was amazed by the work I received. Their expert provided me the instant support and helped me in my assignment. Thank you guys for your assignment help and support.

Puremelda said...

Many students are undecided about the best nursing research paper help Company to deal with due to the high number of companies that offer similar services.

Davis Willa said...

Thanks for sharing. Nice article. I am working as an academic expert in Australia. Our writers provide the best online Sydney assignment help and programming assignment help for college and university students.

MyAssignmentHelp said...

Thank you for sharing this informative post.MyAssignmenthelp.co.uk is giving dissertation 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 Accounting Dissertation Writing to save their time and make life easy.

Puremelda said...

We deliver our nursing essay writing service ahead of deadlines and time frame you specify more often than not, having an insight on the significance of timely submission of the cheap term papers to institution departments.

MATLAB solutions said...

It’s good to share information with others. I am also sharing something very important for students seeking MATLAB Assignment Help. Visit
matlabsolutions.com and get best assistance in your MATLAB, simulink assignments and projects. You can also visit MatlabHelpers for Matlab Assignment Help from Mathworks certified experts that provide online help services to students

meldaresearch said...

Companies offering affordable writing services should help students perform well by delivering papers prior to deadline. Early delivery of custom writing services by our online research paper writer is very important because it results in good performance of learners.

Angel Claudia said...

Students need not struggle so much with their assignments and they should seek our research paper assistance when they can easily get professional research paper help online from us.

meldaresearchusa said...

The assignments we offer students are more advanced than regular free custom essays online and we make sure we clearly understand every instruction client’s provide us before we start our term papers for sale online process.

Unknown said...

Every single college or university student is required to complete number of different homework projects. Meeting the deadlines of their homework is never easy as they not only have to complete one assignment, instead they are bombarded with number of different assignments.\For further information queries visit our website homework help

wemake said...

Download latest audio and video file fromvidmate

Puremelda said...

Are you seeking essay writing help? We are the best writing company providing custom college papers written by highly professional experts. Our nursing paper writing service are experts in their disciplines and have tremendous contributions to their areas of specialty.

Unknown said...

At Assignment studio we have a number of service’s that we have to offer, among them MyAssignmenthelp is one of the most in demand service that majority of the students inquire about. Myassignmenthelp offered by assignment studio is considered to be one of the best assignment help service offered online by a team of professional and experienced academic writers.
For further information queries visit our website myassignmenthelp

Unknown said...

Assignmentstudio.net brings you the high quality online Professional IT Management Assignment Help for all kind of your college and university assignments related to IT management. Our assignment help Melbourne services are the best in assignment help business and highly preferred by students.
For further information queries visit our website it assignment help

Aman Kumar said...

Here I am sharing wonderful platform for students in Australia , US and UK seeking for programming assignment help. This is Programmingshark.com , world's no1 programming help company since 2014. They cover almost all wide range of programming subjects, here you go:
C Programming Assignment Help , C++ Programming Assignment Help , Python Programming Assignment Help , R Programming Assignment Help , and MATLAB Assignment Help . Visit now!

meldaresearch said...

We are the best writing company providing Essay Writer Servicesof the highest quality. We guarantee our customers of nothing but the highest quality document. Our Custom Term Paper Writing Services are well referenced, formatted and edited to ensure that the article is rid of unnecessary details.

Custom Retail Packaging said...

Get your custom printed boxes wholesale from Custom Boxes Zone to protect your product and help your business achieve the highest levels in the market. You can get free designs and free deliveries. We believe in helping our customers to whatever extent we can.

Puremelda said...

Our top-notch writers have access to peer-reviewed articles, Free Essay Writer Services and online databases that are essential in writing Custom Writing Services on any chosen topic.

The Custom Boxes Print said...

The Custom Boxes Print.us has opensd new avenues for custom boxes.Our four colour digital and printing services permit you to possess excellent quality personalised packaging. acquire the box you wish U.S.A. to print from our large choice of product.
The Custom Packaging Boxes
Custom Boxes Wholesale

Online Assignment Help said...

It is valid for any student to ask about the individuals who will write the Coca Cola swot analysis for them. We only assign those writers who are capable of providing the most effective Coca Cola case study help to the students.

Jacob Oram said...

Thanks for sharing this beautiful post. I really enjoyed reading your article. I found this is an informative and interesting post, so I think it is very useful and knowledgeable. Nice effort. Get help from a leading writing company dissertation proposal writing service UK.

Kristine Robinson said...

Our CPM homework helpers use accurate problem-solving strategies to come up with the right answers to each question in this course. Stuck with the questions in the course 1 of CPM? Get CPM homework answers from us now!

unknow said...

I really enjoyed your blog Thanks for sharing such an informative post.
https://myseokhazana.com/
https://seosagar.in/
Indian Bookmarking list
Indian Bookmarking list
India Classified Submission List
Indian Classified List
Indian Bookmarking list
Indian Bookmarking list
India Classified Submission List
Indian Classified List
Friendship Club In India
Friendship Club In Mumbai
Friendship Club In Delhi
Friendship Club
Friendship Chandigarh

Olivia Crew 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. Kindly visit livewebtutors website we providing best assignment help services in Australia.
Read more now :- My Assignment Help

britishcareergroup said...

best ielts coaching institute in mohali
Thank you for sharing such a useful Information.It is worthy to remember that all IELTS training institutes will claim themselves to be the best in the market. But with the right researching and finalizing skills, you can easily find out the best ielts coaching institute in Mohali.When you sign up for the preparation of this course with one of the best ielts coaching institute in Mohali, you will not only be spending your money but also your precious time for a couple of months. So you need to ensure that the lectures are enriching enough and tailored to your requirements. Only then can you gear up on the right path and look forward to fetching brilliant marks in your IELTS examination.
Best IELTS Coaching in Mohali
IELTS coaching
best ielts classes in mohali
ielts training institute in mohali
best ielts institute in mohali

AssignmentWorkHelp said...

assignment website india | homework help india
I like to read your blog. You shared a wonderful information. Thanks for sharing this amazing post.India Assignment writers at Assignment work help are the most reliable writers India. They are so dynamic in nature as they have studied throughout in India and they understand the education system. We offer tailored assignment solutions to the students based on their specific requirements and you can trust Assignment Work Help as the best Indian writers in Australia for high-quality assignments at affordable pricing. The writers are recognized for expertise in preparing assignments for the subjects which are taught in Australian Universities.
indian assignment experts
assignment experts india
assignment help india
assignment writing help india
assignment services india
assignment website india
homework help india

Max Willor said...

I suggest everyone to choose Assignment Help Australia for getting the best guidance in their academia. The proficient experts assist as per the requirements and learning styles desired by the university.