Hooked on Guava

I find myself using Google Guava to manage my Java collections more and more these days.

Below are some examples of Guava features I particularly like.

// instead of
Map<Developer, Integer> devDays = new HashMap<Developer, Integer>();

// write
Map<Developer, Integer> devDays = Maps.newHashMap();

Instead of using for-loops to derive collections from other collections, Guava’s function, predicate and transform mechanisms are fast, declarative, and well-suited to re-use. I recently needed to have a little in-memory database and found Guava’s collection tools effectively became a concise SQL language for querying and transforming my data. Particularly powerful was the ability to create reusable filters and transforms.

Lastly, I find myself often needing a “group by” operation for collections in Java. Guava’s Multimap is fantastic for this. The Multimaps.index() function offers an easy way to create custom indexes on your collections. Here’s an example:

	class Developer {
		final String name;
		final String project;

		public Developer(String name, String project) {
			this.name = name;
			this.project = project;

	public void multimapsIndex() {
		List<Developer> devs = Lists.newArrayList();

		devs.add(new Developer("ken", "chi"));
		devs.add(new Developer("tom", "chi"));
		devs.add(new Developer("cesar", "sdm"));
		devs.add(new Developer("jason", "sdm"));

		Multimap<String, Developer> devsByProject = Multimaps.index(devs,
				new Function<Developer, String>() {
					public String apply(Developer dev) {
						return dev.project;

		for (String project : devsByProject.keySet()) {
			for (Developer dev : devsByProject.get(project)) {
It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply