Thursday, 1 September 2011

Multimaps - Google 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.


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>();

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, 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()) {
  // Removing a single value
  System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]
  // Remove all values for a key
  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.


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:, 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


Balaji said...


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

Java Proficiency said...

visit guava tutorial with well explain examples

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.

qwe qweqwe said...

the '' url points to 'http:://'. 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...

Service iPhone Lampung
Service HP Bandar Lampung

Sharp Indonesia said...

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