Wednesday, February 24, 2010

Java: Google Collections

Starting with tech...


Google Collections API is a great utility library every Java developer should know. It imbibes most of what Joshua Bloch has suggested in his book "Effective Java".

I'm sharing my two cents worth, of what I've read about it, here.

Working with Lists (com.google.common.collect.Lists )

Creating an ArrayList
     List<String> list1 = Lists.newArrayList("1", "2", "3");

For creating an immuable list, instead of using
    List<String> list = new ArrayList<String> ();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
use
    ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");

Same goes for Map
    ImmutableMap<String,String>  map = ImmutableMap.of("key1", "value1", "key2", "value2");

To make it even shorter, create a utility collection of your own and wrap these creational factory methods
    ImmutableMap<String,String>  map2 = mapOf("key1", "value1", "key2", "value2")

Or

    ImmutableList<String> list2 = listOf("a", "b", "c", "d");

Working with Maps: (com.google.common.collect.Maps)

Standard way of creating HashMap using Java Collections
  
   Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long,List<String>>>();

Using google collections

    Map<String, Map<Long, List<String>>> map = Maps.newHashMap();

Better still do this (using static imports)

    Map<String, Map<Long, List<String>>>map = newHashMap();

Google Collections also has an implementation of BiMap that preserves uniqueness of not only keys but also of its values


BiMap<Integer,String> biMap = HashBiMap.create();
biMap.put(Integer.valueOf(5), "Five");

biMap.put(Integer.valueOf(1), "One");

biMap.put(Integer.valueOf(9), "Nine");

biMap.put(Integer.valueOf(5), "One More Five");

biMap.put(Integer.valueOf(55), "Five");

System.out.println(biMap);

System.out.println(biMap.inverse());


would print:

{9=Nine, 55=Five, 1=One, 5=One More Five}

{Nine=9, One More Five=5, Five=55, One=1}


Google Collections enables you to easily build immutable maps via builder:

ImmutableMap<String,Integer> map1 = new ImmutableMap.Builder().put("one", 1).put("two", 2).put("three", 3).build();


ImmutableMap<String,Integer> map2 =new ImmutableMap.Builder<String,Integer>().put("five", 5).put("four", 4)put("three", 3)
.build();

MapDifference difference = Maps.difference(map1, map2);

System.out.println(difference.entriesInCommon());

System.out.println(difference.entriesOnlyOnLeft());

System.out.println(difference.entriesOnlyOnRight());

Here is the result of this snippet:

{three=3}

{one=1, two=2}

{five=5, four=4}


GC offers more for comparators and predicate logic.

Explore more here: http://code.google.com/p/google-collections/

Reference:
http://bwinterberg.blogspot.com/2009/09/introduction-to-google-collections.html
http://publicobject.com/2007/09/series-recap-coding-in-small-with.html

First post

Starting this blog to share some random stuff