Platinum Partner
java,frameworks

Reasons to Use Google Collections

After seeing that Google Collections has just had it's final 1.0 release at the end of last year, I thought that I should take a look to see what the advantages are to using this library rather than the default collections provided in the JDK. Google Collections is available as a zip file containing a jar file, source code and javadoc. 

The Java Collections API is there to be extended, and Google Collections does this very well. Straight away, one of the best things that I see about the library is the inclusion of a MultiMap type.  This allows you to associate multiple values with one key in your map. Seeing this feature made me realise how much wasteful code I've written in the past.

To illustrate this, let's use a phone book example, where each person could have 1 or more phone numbers. Previously, I would have stored the phone numbers in a seperate list per person as follows:

Map<Person, List<PhoneNumber>> phoneBook = new HashMap<Person, List<PhoneNumber>>();

With MultiMap, this is much neater: 

Multimap <Person, PhoneNumber> newPhoneBook = ArrayListMultimap.create();

And with multimap there's no need for managing the lists of phone numbers per person.  When I have a new addition it's just a matter of: 

Person me = new Person("James");
newPhoneBook.put(me, new PhoneNumber(111));
newPhoneBook.put(me, new PhoneNumber(201));

instead of the old verbose way of managing the ArrayList: 

Person me = new Person("James");

if(phoneBook.get(me) == null)
{
phoneBook.put(me, new ArrayList<PhoneNumber>());
}
phoneBook.get(me).add(new PhoneNumber(111));

While on the topic of managing the data that you're processing, the Preconditions allow you to run checks on your parameters that you are passing around.

Preconditions.checkNotNull(me);

I know it's available with assertions in Java, but this way you will always have your checks enabled. You can also easily check, and throw an IllegalArgumentException for a particular argument, by evaluating an expression: 

Preconditions.checkArgument((i > 0), "The value i has to be greater than zero");

There are a number of other useful features such as the ability to create immutable collections quickly: 

ImmutableList<Integer> numbers = ImmutableList.of(1, 2, 3, 5, 8, 13, 21, 34);

Previously you would have needed to create the list as normal, and then use Collections.unmodifiableList(). 

To get a really good overview of the library, check out this video from a 2008 talk by Kevin Bourrillion:

 

In summary, this library gives you a nicer way of dealing with collections, and makes your code much more readable and to the point. 

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}