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.