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

226 comments:

«Oldest   ‹Older   201 – 226 of 226
archi said...

Purchase the best convection microwave oven in india under 10000 with buyers guide and
review. best convection microwave oven under 10000

Hamna Javed said...

gifts delivery in pakistan

Willow harper said...

nice post gifts delivery in Pakistan

sifon said...

Excellent blog post. Thank you for sharing this amazing blog post. Looking forward for more of your post. mth102 past question

Kelly Wilson said...

Thanks for sharing this valuable post.
Do you need Online Assignment Help at a pocket-friendly price? Assignmenthelpaus.com offers assignment help services with zero plagiarism content. We have Assignment Writers who assist you with quality content. You can avail of our services 24/7 through our live chat facility.

Stella Brown said...

Thanks for sharing it. This post is so considerable.
Are you looking for Accounting Assignment Help by a professional accounting expert? We provide assignment help services online at a very cheap price. Students who want the most reliable accounting assignment writing help can visit Assignment Task.

Jamie Marc said...

Thanks for sharing this valuable post.
Are you looking for a Case Study Helper? Casestudyhelp.net provides top-quality writing services. We have experienced writers who assist you with MBA Case Study Help, assignment writing and more at the best price. We offer plagiarism free assistance 24/7 through a live chat facility.

Essien said...

I believe anyone would love and appreciate this blog review. Thank you for a great, knowledge-filled post that made a huge impact on your audience. Thank you for sharing. when will lasu post utme de form be out

Vivian Raddix said...

Very Interesting topic to read. Really great post thanks for the information. Are you Looking for ielts preparation classes in Vadodara? Then join us ielts preparation in Vadodara.

Rob Martin said...

Get the finest assignment help services in UAE from top-qualified MBA/PhD experts at Assignmenttask.com. We are providing online tutoring help for students at a very reasonable cost. A college and university student who requires expert assignment help can get our customized assignment writing services in any subject. For more information, browse us now and avail extra benefits.

Jamie Marc said...

Thanks for sharing this valuable information.
Get Finance Case Study Homework Help by eminent professionals at Casestudyhelp.net. We cover all major topics in case studies. Students can avail any type of Finance Case Study Writing Help at a budget-friendly price. So, your wait is over now. Visit us today!

Jamie Marc said...

Thanks for sharing this wonderful article. Keep it up!
Do you need the most reliable MBA Assignment Help at a budget-friendly price? Want to get assignment writing services by professionals? Casestudyhelp.net is always here to assist you with any academic service. Place your order now!

My Assignment Help said...

Good Blog
Need expert thesis writers in Malaysia to help you with your research work? At MyAssignmenthelp.my, we have a team of skilled and experienced thesis writers who can provide you with top-quality thesis writing help at an affordable price. Contact us today and get your thesis done on time.

Academic Writer Choices said...
This comment has been removed by the author.
blogscomment3322 said...

All the honesty and the companionship that your pet showers on you deserve a reward. Of course, you want to tell your dog that it has done some good. pet articles Incentives can lead your pet to repeat the good work. Such incentives are a part of dog training for dog owners and if done correctly, it can reap many benefits.

Getting Payment Gateways in Europe said...

Get ready to accept credit card payments in person, online, and around the world with a trusted credit card processing from WebPays. Contact WebPays now to experience affordable credit card payment solutions.

ITIO Innovex said...

Are you looking for holistic, frictionless, innovative, customized, and transformative white-label payment gateway solutions to drive more revenue and diversify your business's revenue streams? You've arrived at the right place! At ITIO Innovex, we fine-tune your product roadmap while adhering to testing and compliance standards.

Getting Payment Gateways in Europe said...

WebPays is one of the most trusted providers of innovative and frictionless credit card merchant account services. Experience lower flat-rate credit card processing fees now with WebPays.


Benny Hall said...

Independence Towing of Charlotte is your go-to provider when it comes to professional towing and Roadside Assistance Charlotte. Their prompt and efficient service means they ensure you won't remain stranded on the road for too long.

BearMotion said...

video production services In Birmingham video content services In Birmingham photography services In Birmingham colour grading software video production company birmingham

Benny Hall said...
This comment has been removed by the author.
Van Rental said...

This content consistently provides fresh perspectives, challenging readers to think differently and more critically about familiar topics.

Marwa Marble in Fujaira

assignment helper said...

Dissertation Help Online is a worldwide assignment service provider. Global assignment expert offers assignment services and try to solve doubts related with assignment to their students. Global assignment help has solution for all the educational subjects. Assignment expert help students to achieve good grades in the exam. Our assignments are easy to understand and error free too. We deliver our assignment on time. Our team of experts are good at writing assignment plagiarism free. So stop your search for an assignment writer and connect with us on our website for more information.

Online Assignment Expert said...

As an engineering student, I've encountered my fair share of tough assignments that seemed impossible to tackle on my own. Thankfully, engineering assignment help services have been a game-changer for me. The guidance from experts not only helps me meet deadlines but also deepens my understanding of the material. I think it's worth considering if you're aiming to improve your performance and grasp difficult concepts.

PHD Assistance in Nagercoil - PhD Support said...

Saaira Technologies helps students identify relevant studies and synthesize findings, thereby establishing a strong foundation for their research. This guidance is crucial for demonstrating an understanding of the scholarly landscape.please visit our website
https://saairatechnologies.com/

WINPROFX said...

Great post! If you are looking for the Best Forex Broker in India, then this is the right platform for you. The guide offers a thorough understanding of what to look for in a forex broker, from regulation to trading tools and security features. It’s important to choose a broker that offers low fees, a user-friendly interface, and access to a wide range of currency pairs. With so many options available, this information will help narrow down the choices and ensure you pick the best platform for your trading needs. Don’t miss out on making an informed decision when selecting your forex broker.

«Oldest ‹Older   201 – 226 of 226   Newer› Newest»