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;
		}
	}

	@Test
	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()) {
			System.out.println(project+":");
			for (Developer dev : devsByProject.get(project)) {
				System.out.println("t"+dev.name);
			}
		}
	}
}
It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply