A Better Java Collections Library from Google

25 Oct 2007

I'm working on a project that is going to need extreme performance capabilities, as well as some unique libraries. Of course, any good Open Source practitioner should do some searching and check their deli.cio.us network's bookmarks before writing their own library. I stumbled across the Google Collections library and an article that interviews the authors. This exactly fits the bill. The Google Collections library offers such nice-to-haves as Multimap with a sensible interface (e.g. calling multimap.put(bar, baz) rather than building up a list first). Here's some code from another related Google Collections series of articles to show the before-and-after benefits:


Before:


Map<Salesperson, List<Sale>> map = new Hashmap<SalesPerson, List<Sale>>();



public void makeSale(Salesperson salesPerson, Sale sale) {

List<Sale> sales = map.get(salesPerson);

if (sales == null) {

sales = new ArrayList<Sale>();

map.put(salesPerson, sales);

}

sales.add(sale);

}


After:


Multimap<Salesperson, Sale> multimap = new ArrayListMultimap<Salesperson,Sale>();



public void makeSale(Salesperson salesPerson, Sale sale) {

multimap.put(salesperson, sale);

}