<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codemunchies &#187; google collections</title>
	<atom:link href="http://codemunchies.com/tag/google-collections/feed/" rel="self" type="application/rss+xml" />
	<link>http://codemunchies.com</link>
	<description>Satisfy your cravings</description>
	<lastBuildDate>Mon, 19 Sep 2011 19:32:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Preconditions, Multimaps and partitioning with Google Collections (part 4)</title>
		<link>http://codemunchies.com/2009/11/preconditions-multimaps-and-partitioning-with-google-collections-part-4/</link>
		<comments>http://codemunchies.com/2009/11/preconditions-multimaps-and-partitioning-with-google-collections-part-4/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 09:45:24 +0000</pubDate>
		<dc:creator>Aleksander Stensby</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[google collections]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://codemunchies.com/?p=249</guid>
		<description><![CDATA[Learn to love Multimaps, Preconditions and Set/Map operators in the Google Collections library!]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F11%2Fpreconditions-multimaps-and-partitioning-with-google-collections-part-4%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F11%2Fpreconditions-multimaps-and-partitioning-with-google-collections-part-4%2F&amp;source=codemunchies&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<div class="mceTemp">
<dl id="attachment_283" class="wp-caption alignleft" style="width: 310px;">
<dt class="wp-caption-dt"><a href="http://codemunchies.com/wp-content/uploads/2009/11/bubbles.jpg"><img class="size-medium wp-image-283" title="Bubbles" src="http://codemunchies.com/wp-content/uploads/2009/11/bubbles-300x179.jpg" alt="&lt;div xmlns:cc=&quot;http://creativecommons.org/ns#&quot; about=&quot;http://www.flickr.com/photos/kubina/157669835/&quot;&gt;&lt;a rel=&quot;cc:attributionURL&quot; href=" width=" mce_href=" height="179" /></a></dt>
<dd class="wp-caption-dd">
<div><a rel="&quot;cc:attributionURL&quot;" href="&quot;http://www.flickr.com/photos/kubina/&quot;">http://www.flickr.com/photos/kubina/</a> / <a rel="&quot;license&quot;" href="&quot;http://creativecommons.org/licenses/by-sa/2.0/&quot;">CC BY-SA 2.0</a></div>
</dd>
</dl>
</div>
<p>In <a href="http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/">part one</a>, <a href="http://codemunchies.com/2009/10/diving-into-the-google-guava-library-part-2/" target="_blank">two</a> and <a href="http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3/">three</a> of this blog series we have covered the <a href="http://code.google.com/p/guava-libraries/" target="_blank">Google Guava library</a> and the <a href="http://code.google.com/p/google-collections/" target="_blank">Google Collections library</a>, and how you as a Java developer can benefit from using these libraries to reduce the amount of boilerplate code in your projects. In the final blog post of this series I will walk you through the über collection &#8220;Multimap&#8221; &#8211; which you will all fall in love with and become addicted to;) We will take a look at how you can use Google Collections to do validation with the use of Preconditions, but first, let&#8217;s  take a look at how we can perform Set and Map operations such as intersections, union and difference.</p>
<p><strong>Set intersections, unions and map operations</strong><br />
Something that tends to be quite the hassle (and messy to write) is to do stuff like intersections, unions or diff on two sets. You often end up having to loop over the sets and well, you don&#8217;t want to write that code over and over again. With the Sets class provided by Google Collections, you get stuff like this out of the box (and completely free! <img src='http://codemunchies.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<pre class="brush:java">        HashSet setA = newHashSet(1, 2, 3, 4, 5);
        HashSet setB = newHashSet(4, 5, 6, 7, 8);

        SetView union = Sets.union(setA, setB);
        System.out.println("union:");
        for (Integer integer : union)
            System.out.println(integer);        

        SetView difference = Sets.difference(setA, setB);
        System.out.println("difference:");
        for (Integer integer : difference)
            System.out.println(integer);       

        SetView intersection = Sets.intersection(setA, setB);
        System.out.println("intersection:");
        for (Integer integer : intersection)
            System.out.println(integer);</pre>
<p>From the <a href="http://publicobject.com/2008/08/coding-in-small-with-google-collections.html">Public Object blog</a>:</p>
<blockquote><p><em>&#8220;Unlike the traditional approach, these methods don&#8217;t do any copies! Instead, they return views that delegate to the provided sets. In the occasional case when the copy is worthwhile, there&#8217;s a handy method immutableCopy to give you one.&#8221;</em></p></blockquote>
<p>Similarly, for maps, we have:</p>
<pre class="brush:java">MapDifference differenceMap = Maps.difference(mapA, mapB);</pre>
<p>and with that MapDifference, we can do stuff like:</p>
<pre class="brush:java">differenceMap.areEqual();
Map entriesDiffering = differenceMap.entriesDiffering();
Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
Map entriesInCommon = differenceMap.entriesInCommon();</pre>
<p>Thank you, Google Collections <img src='http://codemunchies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Validation with Preconditions</strong><br />
Bent André, a colleague and newest addition to the Codemunchies clan,  introduced me to this concept earlier this summer, but it wasn&#8217;t until recently that I discovered that Google Collections actually included some of this stuff (we had our own implementation of a similar concept).</p>
<p>So, what is this concept? Well, validation is definitely something we do a lot, and it usually looks like something along these lines:</p>
<pre class="brush:java">        if (count &lt;= 0) {
            throw new IllegalArgumentException("must be positive: " + count);
        }</pre>
<p>We want to validate that the calling method invoked our method with the correct arguments. And if wrong, the caller should be warned that he made en error.</p>
<p>As the Java doc explains:</p>
<blockquote><p><em>&#8220;Precondition exceptions are used to signal that the calling method has made an error. This tells the caller that it should not have invoked the method when it did, with the arguments it did, or perhaps ever. Postcondition or other invariant failures should not throw these types of exceptions.&#8221;</em></p></blockquote>
<p>So, with the Preconditions class (and static imports), we can replace the code above with the following simple line of code:</p>
<pre class="brush:java">checkArgument(count &gt; 0, "must be positive: %s", count);</pre>
<p>Likewise, you have similar methods to check state or null values.</p>
<pre class="brush:java">checkNotNull(entry);</pre>
<p>Quite neat, don&#8217;t you think?</p>
<blockquote><p><em>&#8220;Note that the sense of the expression is inverted; with Preconditions you declare what you expect to be true, just as you do with an assert or a JUnit assertTrue call.&#8221;</em></p></blockquote>
<p>From the excellent <a href="http://publicobject.com/2007/09/coding-in-small-with-google-collections_08.html">blog series on Google Collections</a> over at  <a href="http://publicobject.com">Public Object</a>:</p>
<blockquote><p><em>&#8220;Preconditions provides methods for state validation. It makes input validation compact enough that you&#8217;ll always want to do it! And unlike Java&#8217;s built-in assert, Preconditions is always enabled.&#8221;</em></p></blockquote>
<p>A great example of what I find all over the place in my code at <a href="http://www.integrasco.com" target="_blank">Integrasco</a> is the following:</p>
<pre class="brush:java">    public PostExample(final String title, final Date date, final String author) {
       //some code to validate that title is not null
       //some code to validate that date is not null
       //some code to validate that author is not null

        this.title = title;
        this.date = date;
        this.author = author;
    }</pre>
<p>Now look at how smooth your code becomes with Preconditions:</p>
<pre class="brush:java">    public PostExample(final String title, final Date date, final String author) {
        this.title = checkNotNull(title);
        this.date = checkNotNull(date);
        this.author = checkNotNull(author);
    }</pre>
<p>Is that neat or what?</p>
<p>We will publish a post on this in more detail soon with regards to exceptions and validations, so stay tuned!</p>
<p><strong>One collection to rule them all! &#8211; The Multimap</strong><br />
I can&#8217;t even count how many times I&#8217;ve made a Map where each key can have multiple values and ended up with the Map&lt;K, List&lt;V&gt;&gt; structure.</p>
<p>And the hassle of adding things to such structures go along the lines of:</p>
<pre class="brush:java">    Map&lt;Person, List&lt;BlogPost&gt;&gt; map = new HashMap&lt;Person, List&lt;BlogPost&gt;&gt;();

    public void addBlogPost(final Person author, final BlogPost blogPost) {
        List&lt;BlogPost&gt; blogPosts = map.get(author);
        if (blogPosts == null) {
            blogPosts = new ArrayList&lt;BlogPost&gt;();
            map.put(author, blogPosts);
        }
        blogPosts.add(blogPost);
    }</pre>
<p>Don&#8217;t tell me you haven&#8217;t ever done this? With the Multimap collection from Google Collections, we can do this in the following (very sweet if I may say so) fashion:</p>
<pre class="brush:java">    Multimap&lt;Person, BlogPost&gt; multimap = ArrayListMultimap.create();

    public void addBlogPost(final Person author, final BlogPost blogPost) {
        multimap.put(author, blogPost)
    }</pre>
<p>Whoop, whoop!</p>
<p>Google Collections provides several implementations of Multimaps, for instance HashMultimap if you want to prevent duplicate pairs, TreeMultimap if you need the pairs in natural order, or LinkedHashMultimap if you need the ability to iterate the maps in insertion-order.</p>
<p>Multimaps provides several utility methods as well, go check out the API documentation on <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html">Multimap</a> and <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimaps.html">Multimaps</a>!</p>
<p>Excited yet? Keep reading!</p>
<p><strong>Partitioning collections</strong><br />
I called this section Partitioning, and I guess you could say it is exactly what we covered under &#8220;Filtering Collections&#8221; in the previous blog post of this series, but when we apply these concepts in combination with functions and the Multimap, I think you will realize how powerful it can all be!</p>
<p>Let us pretend that we have a list of Maps. Each Map represent a document with certain attributes. A map may look something like this:</p>
<pre class="brush:java">mapOf("type", "blog", "id", "292", "author", "john");</pre>
<p>I.e., we have three keys, namely &#8220;type&#8221;, &#8220;id&#8221;, and &#8220;author&#8221;.<br />
So our list of maps have the following structure:</p>
<pre class="brush:java">List&lt;Map&lt;String, String&gt;&gt; listOfMaps</pre>
<p>Now, we want to partition our list into several lists, by the type of entry. Let&#8217;s say that one type can be &#8220;blog&#8221;, another could be &#8220;news&#8221;, etc.</p>
<p>Now without Google Collections, that would be a real pain in the ass! We would have to loop the list, check the key of each map, then organize them into individual lists. And the hassle would be even bigger if we don&#8217;t know what types that we have! Following me?</p>
<p>With a little bit of Function magic, and the use of Multimaps, we can do this in a fairly elegant way:</p>
<pre class="brush:java">        Multimap&lt;String, Map&lt;String, String&gt;&gt; partitionedMap = Multimaps.index(
                        listOfMaps,
                        new Function&lt;Map&lt;String, String&gt;, String&gt;() {
                            public String apply(final Map&lt;String, String&gt; from) {
                                return from.get("type");
                            }
                        });</pre>
<p>Now we have a Multimap where each key represents the type!<br />
If we want all the maps for a specific type, all we need to do is ask our multimap for it!</p>
<p>Okay, that&#8217;s it for now! Hope you enjoyed the ride and that maybe you got inspired to check out these really great projects from the developers over at Google! Feedback is highly appreciated!</p>
]]></content:encoded>
			<wfw:commentRss>http://codemunchies.com/2009/11/preconditions-multimaps-and-partitioning-with-google-collections-part-4/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Functional Java, Filtering and Ordering with Google Collections (part 3)</title>
		<link>http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3/</link>
		<comments>http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 14:24:42 +0000</pubDate>
		<dc:creator>Aleksander Stensby</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[google collections]]></category>
		<category><![CDATA[guava]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://codemunchies.com/?p=245</guid>
		<description><![CDATA[Third part of the series on Google Collections and Guava!]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F11%2Ffunctional-java-filtering-and-ordering-with-google-collections-part-3%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F11%2Ffunctional-java-filtering-and-ordering-with-google-collections-part-3%2F&amp;source=codemunchies&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<div class="mceTemp">
<dl id="attachment_274" class="wp-caption alignleft" style="width: 310px;">
<dt class="wp-caption-dt"><a href="http://codemunchies.com/wp-content/uploads/2009/11/bunnies.jpg"><img class="size-medium wp-image-274" title="bunnies" src="http://codemunchies.com/wp-content/uploads/2009/11/bunnies-300x225.jpg" alt="&lt;div xmlns:cc=&quot;http://creativecommons.org/ns#&quot; about=&quot;http://www.flickr.com/photos/audreyjm529/3933104120/&quot;&gt;&lt;a rel=&quot;cc:attributionURL&quot; href=" width=" mce_href=" height="225" /></a></dt>
<dd class="wp-caption-dd">
<div><a rel="&quot;cc:attributionURL&quot;" href="&quot;http://www.flickr.com/photos/audreyjm529/&quot;">http://www.flickr.com/photos/audreyjm529/</a> / <a rel="&quot;license&quot;" href="&quot;http://creativecommons.org/licenses/by/2.0/&quot;">CC BY 2.0</a></div>
</dd>
</dl>
</div>
<p>In <a href="http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/">part one</a> and <a href="http://codemunchies.com/2009/10/diving-into-the-google-guava-library-part-2/" target="_blank">two</a> of this blog series I gave an introduction to the excellent Google Collections and Guava libraries.  In this blog post we will look at how you can use Google Collections to do filtering and ordering! Furthermore, I will show you how we can make Java just a tiny bit more &#8220;functional&#8221; with Google Collections!</p>
<p><strong>Functions, Functions, Functions!! </strong><br />
Google Collections provides us with a couple of very neat things called Functions and Predicates! Similar to some of the magic you can do with for instance Scala, you can now do with good old non-functional Java! You&#8217;ll find these (and more) in the <em>com.google.common.base</em> package in Google Collections.</p>
<p>We will look at Predicates in the next section (on Filtering collections), but first let&#8217;s take a look at Functions!<br />
Google Collections provides us with the interface Function&lt;F, T&gt;. In essence, a function is a transformation from one object to another.</p>
<p>The collection utility classes like Lists and Maps provide us with transformation methods:</p>
<pre class="brush:java">   topMap = Maps.transformValues(fromMap, function);
   toList = Lists.transform(fromList, function);</pre>
<p>To exemplify, let&#8217;s say you have a Map of items and a corresponding price in Euros. So, you figure out that you want an easy way to convert all prices to Dollars. Traditionally we would have to loop through the map and update each value with the converted price. Tedious&#8230;<br />
With functions, this becomes easy!</p>
<pre class="brush:java">Map usdPriceMap = Maps.transformValues(eurPriceMap, new Function() {
            double eurToUsd = 1.4888;
            public Double apply(final Double from) {
                return from * eurToUsd;
            }
        });</pre>
<p>Well, you might say that the anonymous inner class makes this a bit messy, and this function would most likely be something that you want to reuse &#8211; still it demonstrates the functional aspect of things here. (C&#8217;mon please give us closures already!)<br />
Similarly to the example above, we can also use Functions to transform from one object type to a completely different one &#8211; say for instance from an Integer to a String.</p>
<p>We will look further into Functions later in this blog series when I walk you through the Multimap collection and show how we can transform from one collection to a another with a little bit of function magic.</p>
<p><strong>Filtering collections with predicates</strong><br />
One of the most common tasks I encounter when working with data at <a href="http://www.integrasco.com">Integrasco</a> is filtering and ordering large collections.<br />
For the sake of simplicity, let&#8217;s say you have a list of names that you want to filter (in a rather stupid way):</p>
<pre class="brush:java">        List&lt;String&gt; names = listOf("Aleksander", "Jaran", "Integrasco", "Guava", "Java");</pre>
<p>With com.google.common.collect.Iterables and com.google.common.base.Predicates we can filter our list for example to just contain Aleksander or Jaran:</p>
<p>Now I know that sounds pretty stupid, but you can also implement your own Predicates, for example to return names that have a length shorter than say 5 characters (I stole this example from Stephan over at <a href="http://codemonkeyism.com">codemonkeyism.com</a>):</p>
<pre class="brush:java">        Iterable&lt;String&gt; filtered = filter(names, or(or(equalTo("Aleksander"),equalTo("Jaran")), lengthLessThan(5)));</pre>
<p>Which will return us Aleksander, Jaran and Java (since Java is shorter than 5 chars.) The &#8216;or&#8217; part here is a bit messy to read, but bear with me. The &#8216;equalTo&#8217; and &#8216;or&#8217; predicates are given to us for free by the Predicates class.</p>
<p>So to implement that lengthLessThan predicate, all you need to do is:</p>
<pre class="brush:java">    private static class LengthLessThanPredicate implements Predicate&lt;String&gt; {
        private final int length;
        private LengthLessThanPredicate(final int length) {
            this.length = length;
        }
        public boolean apply(final String s) {
            return s.length() &lt; length;
        }
    }</pre>
<p>Wrap that in whatever utility class you want and access it like this:</p>
<pre class="brush:java">    public static Predicate&lt;String&gt; lengthLessThan(final int length) {
        return new LengthLessThanPredicate(length);
    }</pre>
<p>Check out <a href="http://codemonkeyism.com">Stephan</a>&#8216;s blog post on writing <a href="http://codemonkeyism.com/creating-a-fluent-interface-for-google-collections/">fluent interfaces for Google Collections</a> &#8211; It&#8217;s really quite neat!</p>
<p><strong>Sorting / Ordering Collections</strong><br />
Thanks to the java Collections utility class we can do stuff like</p>
<pre class="brush:java">Collections.sort(List&lt;T&gt;, Comparator&lt;? super T&gt;)</pre>
<p>But sometimes we want to do more complex stuff, combining several Comparators and moreover we may want a view of the sorted list, without changing the original order.</p>
<p>Google Collections provides us with Ordering, which allow us greater control over our sorting.<br />
Let&#8217;s say we have two simple comparators for a class Person, that compares by lastName or by firstName:</p>
<pre class="brush:java">        Comparator&lt;Person&gt; byLastName = new Comparator&lt;Person&gt;() {
            public int compare(final Person p1, final Person p2) {
                return p1.getLastName().compareTo(p2.getLastName());
            }
        };
        Comparator&lt;Person&gt; byFirstName = new Comparator&lt;Person&gt;() {
            public int compare(final Person p1, final Person p2) {
                return p1.getFirstName().compareTo(p2.getFirstName());
            }
        };</pre>
<p>Now, if we want to sort by last name first, then by first name, and then return the sorted results in reverse order, all we need to do is:</p>
<pre class="brush:java">        List&lt;Person&gt; sortedCopy = Ordering.from(byLastName).compound(byFirstName).reverse().sortedCopy(persons);</pre>
<p>And even better, you don&#8217;t even need to create Comparators, you can just extend Ordering!</p>
<pre class="brush:java">        List&lt;Person&gt; sortedCopy = orderByLastName.compound(orderByFirstName).reverse().sortedCopy(persons);</pre>
<p><strong>Filtering and Sorting cont&#8217;d</strong><br />
So in part 1 on this blog series, Steve commented that in Scala, you can do stuff like the following:<br />
<code>people.filter(_.firstName == "Steve").sort(_.lastName &lt; _.lastName)</code><br />
i.e. get people named Steve from the list people, and then sort by their last name.</p>
<p>Syntactically, that line of Scala code is pretty neat! So let&#8217;s see what we can do with Google Collections then. Google Collections provides us with the Iterables class that we covered earlier in this blog post (under filtering). We can do both filter and transform with the Iterables class (and you can do the same with Collections2, provided by Google Collections as well).<br />
So I wanted to have a crack at how to solve the same thing as Steve did with his line of Scala code, and even though it is not as neat, this is one way of solving the above Scala code with the use of Predicates and Ordering:</p>
<pre class="brush:java">   Ordering.from(byLastName).sortedCopy(filter(persons, withFirstName("Steve")));</pre>
<p>Still not close to the syntactical sugar we get from Scala (and obviously we would need our &#8220;withFirstName&#8221; predicate and the &#8220;byLastName&#8221; Comparator), but at least this is much closer than where we were without Google Collections! (And it would become even easier to read if we take on Stephen&#8217;s approach to fluent interfaces).</p>
<p>As Kevin Bourrillion commented on another <a href="http://blogs.warwick.ac.uk/chrismay/entry/writing_functional_java/">blog post on writing functional Java</a>:</p>
<blockquote><p><em>&#8220;The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I&#8217;m undecided how much effort to put into the Function/Predicate stuff; it&#8217;s in the library more because it sort of had to be, not so much because we think it&#8217;s a crown jewel.&#8221;</em></p></blockquote>
<p>In the next and final part of this blog series on Google Collections and Guava we will take a look at Set and Map operators in Google Collections, Validation with Preconditions and I will walk you through the wonderful Multimap collection and how we can use this for partitioning!</p>
<p>Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Diving into the Google Guava library (part 2)</title>
		<link>http://codemunchies.com/2009/10/diving-into-the-google-guava-library-part-2/</link>
		<comments>http://codemunchies.com/2009/10/diving-into-the-google-guava-library-part-2/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 09:23:59 +0000</pubDate>
		<dc:creator>Aleksander Stensby</dc:creator>
				<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[google collections]]></category>
		<category><![CDATA[guava]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://codemunchies.com/?p=243</guid>
		<description><![CDATA[Dive into the advanced features that Guava offers to you as a Java developer!]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F10%2Fdiving-into-the-google-guava-library-part-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F10%2Fdiving-into-the-google-guava-library-part-2%2F&amp;source=codemunchies&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://codemunchies.com/wp-content/uploads/2009/10/balloons.jpg"><img class="size-medium wp-image-240" title="Balloons" src="http://codemunchies.com/wp-content/uploads/2009/10/balloons-300x205.jpg" alt="</p>
<div xmlns:cc=&quot;http://creativecommons.org/ns#&quot; about=&quot;http://www.flickr.com/photos/pinksherbet/345653550/&quot;><a rel=&quot;cc:attributionURL&quot; href=" width=" mce_href=" height="205" /></a>In <a href="http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/">part one</a> of this blog series I gave an introduction to the excellent Google Collections and Guava libraries and briefly explained how you as a Java developer can benefit from using Guava with Collections to reduce the amount of boilerplate code in your projects. In this blog post we will dive deeper into the more advanced features that Guava offers to you as a Java developer!</p>
<p>We will take a deeper dive into Guava and look at the really neat CharMatcher class, the Joiner and Splitter classes and what else Guava brings us when it comes to working with primitives.</p>
<p><strong>The Guava CharMatcher</strong><br />
The CharMatcher class in Guava is a quite neat addition to your Java toolbox! Some people call it <em>&#8220;StringUtils on steroids&#8221;</em>:p<br />
Out of the box you have access to some predefined constant matchers like CharMatcher.WHITESPACE, CharMatcher.JAVA_DIGIT or CharMatcher.ASCII, and in addition you have some neat factory methods like CharMatcher.is(&#8216;aaa&#8217;), CharMatcher.isNot(&#8216;bbb&#8217;), CharMatcher.oneOf(&#8216;abcd&#8217;).negate() and even more complex things like:</p>
<pre class="brush:java">CharMatcher.inRange('a', 'z').or(inRange('A', 'Z'));</pre>
<p>You can also subclass it and implement the matches(char c) method. You can even create one from one of your Google Collection Predicates (that we will cover next time)!</p>
<p>So, if you want to get all the digits from a piece of text, all you need to do is:</p>
<pre class="brush:java">String string = CharMatcher.DIGIT.retainFrom("some text 89983 and more");</pre>
<p>You want to go the other way around and remove all digits from a string, simply do the following:</p>
<pre class="brush:java">String string = CharMatcher.DIGIT.removeFrom("some text 89983 and more");</pre>
<p>For matching purposes you have several methods like:<br />
matchesAllOf(CharSequence)<br />
matchesAnyOf(CharSequence)<br />
matchesNoneOf(CharSequence)</p>
<p>You also have indexIn, lastIndexIn and countIn methods in addition to several methods for trimming, replacing and collapsing.<br />
Check out the <a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/CharMatcher.html">Java doc</a> for more info!</p>
<p><strong>Joiner and Splitter </strong><br />
The Joiner class is currently part of Collections and the Splitter class is found in Guava (but will ultimately join hands in Guava, once Collections get it&#8217;s 1.0 release).<br />
With the Joiner class, we can do stuff like this:</p>
<pre class="brush:java"> String[] subdirs = { "usr", "local", "lib" };
 String directory = Joiner.on("/").join(subdirs);</pre>
<p>or this:</p>
<pre class="brush:java"> int[] numbers = { 1, 2, 3, 4, 5 };
 String numbersAsString = Joiner.on(";").join(Ints.asList(numbers));</pre>
<p>Thanks to Guava we can also join directly on primitives, which is quite handy:</p>
<pre class="brush:java"> String numbersAsStringDirectly = Ints.join(";", numbers);</pre>
<p>For Strings we can obviously split directly, but the behavior is somewhat strange, and the Splitter class is more robust and gives us more options. Also, String split always returns and array as where the Splitter class returns us an Iterable.</p>
<pre class="brush:java">Iterable split = Splitter.on(",").split(numbsAsString);</pre>
<p>With the String split you can simply do:</p>
<pre class="brush:java">String[] splitRegular = testString.split(",");</pre>
<p>But try doing that with a String like this one:</p>
<pre class="brush:java">String testString = "foo , what,,,more,";</pre>
<p>Output would be:<br />
&#8216;foo &#8216;<br />
&#8216; what&#8217;<br />
&#8221;<br />
&#8221;<br />
&#8216;more&#8217;<br />
And that might be fine, but the Splitter class let&#8217;s us gain more control over the desired output of the splitting:</p>
<pre class="brush:java">Iterable&lt;String&gt; split = Splitter.on(",").omitEmptyStrings().trimResults().split(testString);</pre>
<p>Giving us the output &#8216;foo&#8217;,'what&#8217;,'more&#8217;</p>
<p>Both the Joiner and Splitter classes are configurable and you can even use the Joiner on maps!</p>
<p><strong>Working with primitives cont&#8217;d</strong><br />
In part one of this blog series I briefly mentioned working with primitives and that Guava offers things like <code>Ints.compare(a, b)</code> and <code>Ints.toArray(list)</code>.</p>
<p>Let me just introduce you to a couple of more handy things that Guava offers when it comes to working with primitives.</p>
<p>Let&#8217;s say we have an array of ints, and we want to know if that array contains a specific int. The old way of doing that would look something like this:</p>
<pre class="brush:java"> int[] array = { 1, 2, 3, 4, 5 };
 int a = 4;
 boolean hasA = false;
 for (int i : array) {
 if (i == a) {
 hasA = true;
 }
 }</pre>
<p>With Guava, we can do this:</p>
<pre class="brush:java">boolean contains = Ints.contains(array, a);</pre>
<p>And again, we can do this with all the other primitives as well! We can even do things like this directly in our array:</p>
<pre class="brush:java"> int indexOf = Ints.indexOf(array, a);
 int max = Ints.max(array);
 int min = Ints.min(array);
 int[] concat = Ints.concat(array, array2);</pre>
<p>In the next post in this series we will take a look at the more advanced features of the Google Collections library such as Functions, Filtering and Ordering! Stay tuned, and please share your comments with us!</p>
]]></content:encoded>
			<wfw:commentRss>http://codemunchies.com/2009/10/diving-into-the-google-guava-library-part-2/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Beautiful code with Google Collections, Guava and static imports &#8211; Part 1!</title>
		<link>http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/</link>
		<comments>http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 12:33:02 +0000</pubDate>
		<dc:creator>Aleksander Stensby</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[google collections]]></category>
		<category><![CDATA[guava]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://codemunchies.com/?p=105</guid>
		<description><![CDATA[Make your code cleaner, faster to write, and get rid of that boiler plate code we all hate so much!]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F10%2Fbeautiful-code-with-google-collections-guava-and-static-imports-part-1%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodemunchies.com%2F2009%2F10%2Fbeautiful-code-with-google-collections-guava-and-static-imports-part-1%2F&amp;source=codemunchies&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<div id="attachment_130" class="wp-caption alignleft" style="width: 310px"><a href="http://codemunchies.com/wp-content/uploads/2009/10/tetris.jpg"><img class="size-medium wp-image-130" title="tetris" src="http://codemunchies.com/wp-content/uploads/2009/10/tetris-300x225.jpg" alt="Tetris cookie?" width="300" height="225" /></a><p class="wp-caption-text">http://www.flickr.com/photos/mache/ / CC BY 2.0</p></div>
<p>So I&#8217;ve been advocating <a href="http://code.google.com/p/google-collections/">Google Collections</a> to all my colleagues since early this summer. Kevin Bourrillion said that one of his colleagues had told him that &#8220;<em>not being able to use the Google Collections was like &#8216;coding with one hand tied behind his back.&#8217;</em>&#8220;.</p>
<p>I couldn&#8217;t agree more with Kevin&#8217;s colleague!</p>
<p>Maybe the title of this blog entry is a bit strange. I mean &#8220;beautiful code&#8221;. I guess I could have said &#8220;less verbose&#8221; Java code, but hey, that doesn&#8217;t have the same magic sound to it!</p>
<p>Before I start this whole highly promotional rant about my new favorite java libraries, let me ask you a couple of questions:<br />
How many times have you written something like this in your code:</p>
<pre class="brush:java">Map&lt;String, Map&lt;Long, List&lt;String&gt;&gt;&gt; map = new HashMap&lt;String, Map&lt;Long,List&lt;String&gt;&gt;&gt;();</pre>
<p>Or maybe something along these lines:</p>
<pre class="brush:java">int a = 5;
int b = 10;
int compareTo = Integer.valueOf(a).compareTo(Integer.valueOf(b));</pre>
<p>(Or with lots of ifs and elses;))</p>
<p>And how many times have you written something along these lines, just to read something from a file?:</p>
<pre class="brush:java">File file = new File(getClass().getResource("/test.txt").getFile());
BufferedReader reader;
String text = "";
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
text += line.trim() + "\n";
}
reader.close();
reader = null;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}</pre>
<p>Yeah, I thought so&#8230; So what&#8217;s all the fuzz about? We&#8217;ve had Apache Commons Collections for several years. Why should we use yet another collections library?<br />
I&#8217;ve read several comments like this one:</p>
<blockquote><p>&#8220;Any Java programmer who&#8217;s been around awhile will already have accumulated most of these types of utility classes.&#8221;</p></blockquote>
<p>Well, yes, that might be (and should hopefully) be true for most developers. But then again, there&#8217;s so much more to it than just getting rid of boiler plate code and reusing nifty utils! In this blog post I want to show you some of the things that really made me curious about &#8211; then later addicted to &#8211; Google Collections.</p>
<p>Like Jared Levy once said:</p>
<blockquote><p>The library&#8217;s functionality simplifies your code so it&#8217;s easier to write, read, and maintain. While you can survive without such features, the Google Collections Library will improve your productivity as a developer, while reducing the amount of boilerplate low-level code you need to write.</p></blockquote>
<div id="attachment_125" class="wp-caption alignleft" style="width: 310px"><a href="http://codemunchies.com/wp-content/uploads/2009/10/360573116_62deaccced_b.jpg"><img class="size-medium wp-image-125" title="360573116_62deaccced_b" src="http://codemunchies.com/wp-content/uploads/2009/10/360573116_62deaccced_b-300x200.jpg" alt="Cookies?" width="300" height="200" /></a><p class="wp-caption-text">http://www.flickr.com/photos/orcaman/ / CC BY 2.0</p></div>
<p>Furthermore I want to show you some of the cool stuff that the guys over at Google have been churning up under the name <a href="http://code.google.com/p/guava-libraries/">Guava</a>, and how <strong>YOU</strong> as a Java developer can utilize these nifty libraries to make your code cleaner, faster to write, and once and for all get rid of <del datetime="2009-10-12T07:49:54+00:00">all</del> a lot of that boiler plate code we all hate so much!</p>
<p>Google Guava is the Google Core Libraries for Java 1.6. It is still a rather immature library that is subject to changes over the coming months, but will eventually be THE Java library;) Google Collections will become part of Guava once Collections reaches it&#8217;s 1.0 release. Guava (and Google Collections) have been pioneered by several Google developers and is widely used in their &#8220;myriad of Java projects&#8221;. Among others, the people behind it are <a href="http://twitter.com/kevinb9n">Kevin Bourrillion</a>, Jared Levy, <a href="http://twitter.com/crazybob">Crazy Bob Lee</a>, Josh Bloch(!) (Chief Java Architect at Google etc.) and limpbizkit (have no clue what this guy&#8217;s name is &#8211; anyone?:p). Google Collections has been around since 2007 (I think?) but Guava saw the light of day in September 2009.</p>
<p>In part one of this blog series I&#8217;ll give you an introduction to Google Collections and show you how you can benefit from using Guava with Collections to reduce the amount of boilerplate code in your projects (and gain access to the new and faster data structures that they provide!). In part 2 we will dive deeper into the more advanced features that Guava and Collections offers to you as a Java developer, so stay tuned!</p>
<p><strong>Google Collections at a glance</strong><br />
Obviously one blog post will not give Google Collections the amount of in-depth coverage it deserves, so I&#8217;ve decided to just spend some time with the basic yet powerful features that I use on a daily basis when I write code.<br />
First of all, don&#8217;t do this:</p>
<pre class="brush:java">Map&lt;String, Map&lt;Long, List&lt;String&gt;&gt;&gt; map = new HashMap&lt;String, Map&lt;Long,List&lt;String&gt;&gt;&gt;();</pre>
<p>Do this:</p>
<pre class="brush:java">Map&lt;String, Map&lt;Long, List&lt;String&gt;&gt;&gt; map = Maps.newHashMap();</pre>
<p>or rather this, (with static imports):</p>
<pre class="brush:java">Map&lt;String, Map&lt;Long, List&lt;String&gt;&gt;&gt;map = newHashMap();</pre>
<p>Nice, right? Thanks to generics and those handy factory methods that the Collections guys have provided us with, we no longer have to write things that Java really should understand, right? Yeah, I know this will be part of JDK 7, and that&#8217;s great. But Google Collections is here, now!</p>
<p>Similar to the static utility methods that com.google.common.collect.Maps provide, we also have Lists and Sets.</p>
<pre class="brush:java">Lists.newArrayList();
Sets.newHashSet();</pre>
<p>&#8230;and more! <a href="http://code.google.com/p/google-collections/">Go check it out for yourself</a>!</p>
<p><strong>Populating lists and maps</strong><br />
When writing unit tests you often want to populate lists (or maps, or sets) with dummy data, and as the sloppy &#8220;duct-tape&#8221; programmer that I am, I&#8217;ve found the same code over and over again in my tests, along these lines:</p>
<pre class="brush:java">List&lt;String&gt; list = new ArrayList&lt;String&gt;();
list.add("a");
list.add("b");
list.add("c");
list.add("d");</pre>
<p>Yeah, I know. Dirty. I want an immutable list, populated with my dummy data, and I want to do it with one line of code! How? Well, that&#8217;s easy!</p>
<pre class="brush:java">ImmutableList&lt;String&gt; of = ImmutableList.of("a", "b", "c", "d");</pre>
<p>Same goes for Maps!</p>
<pre class="brush:java">ImmutableMap&lt;String,String&gt; map = ImmutableMap.of("key1", "value1", "key2", "value2");</pre>
<p>I&#8217;ve grown really fond of these simple, yet powerful ways of writing code now. I wanted to write that line in an even shorter way, but couldn&#8217;t do it out of the box with static imports since both ImmutableList and ImmutableMap had the method &#8220;of&#8221;. But a quick workaround was simply to wrap these creational factory methods (and builder methods that they provide) in a collection util of our own. So for immutable maps and lists I simply write:</p>
<pre class="brush:java">ImmutableMap&lt;String,String&gt; map2 = mapOf("key1", "value1", "key2", "value2")</pre>
<p>or</p>
<pre class="brush:java">ImmutableList&lt;String&gt; list2 = listOf("a", "b", "c", "d");</pre>
<p>And if I want to populate an ArrayList (or a HashMap) I use:</p>
<pre class="brush:java">ArrayList&lt;String&gt; list3 = arrayListOf("a", "b", "c", "d");</pre>
<p>The choice is yours, obviously, but you have to admit, it&#8217;s quite neat compared to the &#8220;old&#8221; way, right?<br />
Apart from the handy and clean ways of creating collections and populating them, we are also provided with lots of additional utility methods like filtering, set intersections and union, ordering and even some neat functional stuff! I&#8217;ll cover that in part 2!</p>
<p><strong>Static imports and Eclipse templates</strong><br />
Before I wrap this up I want to tell you about how I use Collections even more efficiently when I code by using the Eclipse Code templates. (I assume you have similar features in IDEA and other IDE&#8217;s, so you can probably follow this recipe to some extent anyways):</p>
<p>Being a user of Eclipse I love shortcuts (check out Jaran&#8217;s post about <a href="http://codemunchies.com/2009/10/mousefeed-learn-your-eclipse-shortcuts/">MouseFeed and how you can easily learn Eclipse shortcuts</a>).<br />
Okay, Ctrl+Space is your friend! It&#8217;s also known as auto-complete:)<br />
With Eclipse, you can create a template that binds to an auto-complete key-word and this is where the magic begins!<br />
Instead of having to write Maps.newHashMap() or (even better &#8211; adding the method as a static import and writing newHashMap()) i simply type &#8220;newH&#8221;, hit ctrl+space and MAGIC! <img src='http://codemunchies.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Go to Window &#8211; Preferences in Eclipse. Go to Java -&gt; Editor -&gt; Templates and hit &#8220;New&#8221;.<br />
The Name will be your shortcut, I usually name mine the method, i.e. &#8220;newHashMap&#8221; in this case.<br />
Add your description if you like, for instance &#8220;Import static Maps.newHashMap&#8221;<br />
And add the following Pattern:<br />
<code>${:importStatic(com.google.common.collect.Maps.newHashMap)}newHashMap();${cursor}</code><br />
And that&#8217;s all there is to it! Now go crazy and add templates for all those method that you use alot!</p>
<p><strong>Guava at a (very quick) glance</strong><br />
Last but not least, let me show you how you can use Guava to deal with the two remaining question I opened this blog post with:<br />
Read lines from a file:</p>
<pre class="brush:java">File file = new File(getClass().getResource("/test.txt").getFile());
List&lt;String&gt; lines = null;
try {
lines = Files.readLines(file, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}</pre>
<p>Compare two primitives?</p>
<pre class="brush:java"> int compare = Ints.compare(a, b);</pre>
<p>Convert a list of Integers to an array of primitive ints?</p>
<pre class="brush:java">List&lt;Integer&gt; list = listOf(1, 2, 3, 4);
int[] array2 = Ints.toArray(list);</pre>
<p>Guava provides us with a comprehensive extension to the Core Java Libraries. Among other things we gain access to utilities for working with primitives through the Ints, Doubles, Floats, Shorts, Bytes and Bools classes in the com.google.common.primitives package. The com.google.common.io package provides utilities for working with streams, buffers, files etc, and the concurrent package provides classes like Futures, Callables and Executors to ease the pain of writing concurrent code. In addition to all of this, Guava also provides us with some additions to Collections and a really neat CharMatcher class, Joiner and Splitter classes that I will cover next time!</p>
<p>Check out the source code here:<br />
svn checkout <a href="http://guava-libraries.googlecode.com/svn/trunk/guava-libraries-read-only">http://guava-libraries.googlecode.com/svn/trunk/guava-libraries-read-only</a></p>
<p>Next time we&#8217;ll take a deeper dive into Guava and also some of the more advanced stuff in Google Collections like how we can make Java just a tiny bit more &#8220;functional&#8221;, the über collection &#8220;Multimap&#8221; and how we can use mapping functions to transform collections. Stay tuned, and please share your comments on this with us! Have you tried Guava or Google Collections? What are your thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://codemunchies.com/2009/10/beautiful-code-with-google-collections-guava-and-static-imports-part-1/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
	</channel>
</rss>

