Taste of Google Guava
Not heard about Google Guava yet? Never mind! We’re gonna change that now.
Google Guava is kind of a “Modern Commons” library and imho every Java Developer should use it on a daily basis. It greatly reduces code clutter and improves code quality due to useful utils and functional programming style. Continue reading to taste Guava!
How to get it? You use a dependency management system that understands maven coordinates, right? Here you go:
Got it? Good, let’s get hands on with a couple of simple examples. In (enterprise) applications we do a lot of object conversions i.e. from DTOs to Domain Objects, from Objects to Strings, etc. Lets say we want to convert a list of UserDTO objects to a List of User Domain Objects:
This simple example shows the functional-style programming (at least with the given limited java capacities): A converting function is used to transform the DTOs to Domain Objects and the result is copied to an immutable list.
The cool thing is that the Anonymous Inner Function can be refactored to its own class or an Util class in case it is, or mighty be reused:
The com.google.common.collect package contains a lot of highly usable convenience and util classes:
Iterables, Iterators and Collections2. Here’s an example:
Tired of clumsy generic type definition constructs like this?
Simply use the Maps util class:
Readable, isn’t it? There are Util classes for each collection type like Lists, Sets, etc.
Need more sophisticated Maps? This example might not make any sense, but shows the power of Maps created with MapMaker:
What about making a comma separated value string out of domain objects?
Let’s take a look on the “old fashioned” imperative style first:
And heres the Guava way:
Result is: ‘test1′, ‘test2′, ‘test3′
Result is ‘b1234b’. More readable compared to regex, isn’t it?
Please note that CharMatcher is Beta API! Thx to Patrick for the hint:
“Anyway (more importantly and more on topic) when talking about Guava you should not neglect to mention @Beta APIs (you are even using some (CharMatcher) in your examples without explaining their potentially dangerous behavior) basically it is never save to use @Beta APIs in any library project without repackaging the classes.”
Read the “important warnings” on the Guava Homepage before using Beta APIs!
One of the Hightlights, at least for me, are Multimaps. A Multimap allows to map multiple values to one key out of the box:
Enough candy for now. Go and taste it yourself!
Also look at the libraries source code to learn modern and good-practice coding techniques in Java.