Thursday, 28 March 2013

Guava : Using Java Collections the Google Way

Recently Guava came out with release 14.0.1 which include a number of bug fixes and enhancements. As a utility library, Guava provides an impressive list of extensions and tools for using Java collections with an aim towards improving code readability, transparently managing Java collections and introducing useful checks and frequently used utility methods that simplify the generation of quality code.
With respect to Java Collections, Guava provides utility methods for creating Immutable collections, and provides some new Collections. If just looking for implementing various checks on your Java Collections, there are a number of Collection Utilities that allow you to create an equivalent Java Collection while writing code that is cleaner and easier to read.

For example, constructing a generic collection before Java 7 would amount to the following line of code:
  • List list = new ArrayList();

In Guava, this could be simplied to  List list = Lists.newArrayList();
And this approach could be further extended to include the List size and initialise the List as follows:
  • List list = Lists.newArrayList(100); // create a list with a 100 elements.
  • List list = Lists.newArrayList("red","blue","green"); // create and initialise a list with some values
Similarly Guava has many utility methods for dealing with nulls in Collections, managing String and performing operations on the Java Math library that is not available in the JDK. If using the Apache Commons Library, Guava is definitely worth a check out !!

No comments: