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.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>
To make it even shorter, create a utility collection of your own and wrap these creational factory methods
ImmutableMap<String,String>
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
ImmutableMap<String,Integer> map2 =new ImmutableMap.Builder
.build();
MapDifference
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
No comments:
Post a Comment