<?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>Jayway Team Blog &#187; collections</title>
	<atom:link href="http://blog.jayway.com/tag/collections/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Getting around static typing in Scala</title>
		<link>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/</link>
		<comments>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 19:43:12 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4503</guid>
		<description><![CDATA[I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. ]]></description>
			<content:encoded><![CDATA[<p>I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. I've run the following code in Scala 2.8</p>
<pre class="brush:scala">
// this is easy since everything are Strings
scala> List("one", "two", "three")
res0: List[java.lang.String] = List(one, two, three)

scala> res0.foreach(x => println(x.length()))
3
3
5

// with a mixed collection it gets harder
scala> List("one", 2, "three", 4.0)
res2: List[Any] = List(one, 2, three, 4.0)

scala> res2.foreach(x => println(x.length()))
&lt;console&gt;:6: error: value length is not a member of Any

// it is not enough to just filter out the objects that are Strings
scala> res2.filter(_.isInstanceOf[String])
res4: List[Any] = List(one, three)

// as we still have a List of Any
scala> res4.foreach(x => println(x.length()))
&lt;console&gt;:7: error: value length is not a member of Any

// both filtering and mapping is needed
scala> res2.filter(_.isInstanceOf[String]).map(_.asInstanceOf[String])
res6: List[String] = List(one, three)

// finally it works
scala> res6.foreach(x => println(x.length()))
3
5

// another option is to use pattern matching
scala> res2.foreach(_ match { case x:String => println(x.length); case _ => })
3
5
</pre>
<p>I wanted a more elegant solution with less boiler plate so after playing around with <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766">implicit conversions</a> and <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types</a> I managed to come up with rather nice solution:</p>
<pre class="brush:scala">
// define a class that implements a restrictTo method
scala> class IterableWithRestrictTo[A](from:Iterable[A]) {
     | def restrictTo[B](implicit m: scala.reflect.Manifest[B]) = {
     | from.filter(m.erasure.isInstance(_)).map(_.asInstanceOf[B])
     | }
     | }
defined class IterableWithRestrictTo

// define implicit conversion
scala> implicit def makeIterableWithRestrictTo[A](from : Iterable[A]) = {
     | new IterableWithRestrictTo(from)
     | }
makeIterableWithRestrictTo: [A](from: Iterable[A])IterableWithRestrictTo[A]

scala> List("one", 2, "three", 4.0)
res0: List[Any] = List(one, 2, three, 4.0)

// restrict to objects of type String
scala> res0.restrictTo[String]
res1: Iterable[String] = List(one, three)

// works since the collection have correct type
scala> res1.foreach(x => println(x.length()))
3
5
</pre>
<p>Using the name restrictTo clearly shows that not only is there a type conversion, but also a restriction to a subset of the elements. Notice that the manifest is needed to get the reified type, since the type B is actually erased at compile time. Read more about <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types in Scala</a>.</p>
<p>Let me know you have another solution! </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Google Collections</title>
		<link>http://blog.jayway.com/2009/10/22/google-collections/</link>
		<comments>http://blog.jayway.com/2009/10/22/google-collections/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 12:10:41 +0000</pubDate>
		<dc:creator>Sune Simonsen</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[bimap]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[multimap]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[ordering]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2052</guid>
		<description><![CDATA[Google Collections is a natural evolution from the standard collections API in Java, bringing a much broader range of functionality to the existing collections and also providing several new collections for its users. The library plays nice with the standard collections and uses existing functionality where possible. Here is a list of useful facts before [...]]]></description>
			<content:encoded><![CDATA[<p>
Google Collections is a natural evolution from the standard collections API in Java, bringing a much broader range of functionality to the existing collections and also providing several new collections for its users. The library plays nice with the standard collections and uses existing functionality where possible.
</p>
<p>
Here is a list of useful facts before we throw ourselves into the code.
</p>
<ul>
<li>Open Source Apache 2 library </li>
<li>Hosted at Google Code: <a title="Project page" href="http://google-collections.googlecode.com/">http://google-collections.googlecode.com/</a></li>
<li>Requires Java 1.5</li>
<li>1.0 Release Candidate 3 now</li>
<li>25,000 unit tests</li>
<li>Used by Google in production</li>
</ul>
<h3>Immutable Collections</h3>
<p>
A big part of the collections library is focused on immutability, the reason for this is the increased demand for concurrent code in order to be able to utilize the ever increasing number of cores in modern computers.
</p>
<p>
Immutable data are thread-safe because it can never be changed and can therefore be shared between multiple threads without worrying. This is a huge improvement because of the complexity involved writing thread safe code that uses mutable data. furthermore immutable data can be handed to untrusted code without worrying about the data being changed by the untrusted code, this really helps sustaining the security boundaries of your system.
</p>
<p>
Another benefit of using immutable collections is that they are in most cases more memory efficient and perform better than the regular collections.
</p>
<p>
In a way it was also possible to create immutable collections with the standard Java API, as an example a set could be made immutable the following way:
</p>
<pre class="java">&nbsp;
Set&lt;Integer&gt; numbers = <span style="color: #000000; font-weight: bold;">new</span> TreeSet&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
Set&lt;Integer&gt; immutableNumbers = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">unmodifiableSet</span><span style="color: #66cc66;">&#40;</span>numbers<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
With Google Collections it would look the following way:
</p>
<pre class="java">&nbsp;
ImmutableSet&lt;Integer&gt; immutableNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
There are several things that are better in the version using Google Collections. You only need to know about the <i>ImmutableSet</i> class, where as in the standard Java version, four classes are combined to achieve the same effect, that is just confusing. When using the <i>new</i> keyword to construct generic classes, the generic type can't be inferred from the constructor arguments, this limitation is not present for methods. Google Collections uses static factory methods to create their collections meaning the generic type will be inferred in this case and therefore turning the code noise down. The third benefit is that the immutable collections are guaranteed to be immutable where as an unmodifiable collection is just an immutable view of the collection and can be changed by code holding a reference to the actual collection. The last benefit is that the information about immutability is captured in the type and clients of this type therefore will be able to count on that the collection is immutable, which means that defensive copying is unnecessary. Be aware that it is only the collection that is promised to be immutable, if the objects contained in the collection are not immutable they can still be changed. Notice that <i>ImmutableSet</i> implements the <i>Set</i> interface so it can be used seamlessly with existing code.
</p>
<p>
Those of you who are familiar with functional programming languages, may expect, that mutating methods like <i>add</i> returns a modified copy of the collection. But in order to implement the standard Java collections interfaces, this is not possible, so instead they just throw an exception. You can of cause still combine existing immutable collections into new ones. If you for example want to create the union of two sets, you can do it the following way:
</p>
<pre class="java">&nbsp;
ImmutableSet&lt;Integer&gt; lowNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span>;
ImmutableSet&lt;Integer&gt; highNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span>,<span style="color: #cc66cc;">10</span>,<span style="color: #cc66cc;">11</span>,<span style="color: #cc66cc;">12</span>,<span style="color: #cc66cc;">13</span>,<span style="color: #cc66cc;">14</span>,<span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span>;
SetView&lt;Integer&gt; union = Sets.<span style="color: #006600;">union</span><span style="color: #66cc66;">&#40;</span>lowNumbers, highNumbers<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
Notice how we use the static <i>union</i> method on the <i>Sets</i> class to create a new <i>SetView</i> based on the two given sets. The <i>SetView</i> is an unmodifiable implementation of the standard <i>Set</i> interface but can change if the underlying collections changes. Google Collections provide similar convenience classes for working with all the popular collections interfaces from the standard Java API, improving your productivity a lot. </p>
<p>Numerous immutable collections exist in the library, for more information see the <a title="API documentation" target="blank" href="http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html">API documentation</a>.</p>
<h3>New collections types</h3>
<p>
Google Collections also provides implementations of a few collections that is not included in the standard Java. These collections can be very useful in special cases.
</p>
<h4>Multisets</h4>
<p>
Multiset is a very useful collection for collecting statistic data of some kind. The collection is basically just a set where a count of how many instances has been added of each element is maintained. So if we as an example want to count the occurrences of each number in a list of numbers it can be done the following way.
</p>
<pre class="java">&nbsp;
ImmutableList&lt;Integer&gt; numbers = ImmutableList.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span>;
Multiset&lt;Integer&gt; multiset = TreeMultiset.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span>numbers<span style="color: #66cc66;">&#41;</span>;
multiset.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Decreasing the count for 0 by 1</span>
multiset.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Increasing the count for 1 by 4</span>
&nbsp;</pre>
<p>
The resulting multiset after adding the list of numbers contains to following information:</p>
<ul>
<li>0 has 1 occurrences</li>
<li>1 has 6 occurrences</li>
<li>2 has 3 occurrences</li>
<li>3 has 3 occurrences</li>
</ul>
<p>
Numerous implementations of the Multiset exists, so it is a good idea to match your requirement against the capabilities of the different implementations before choosing one.
</p>
<h4>Multimaps</h4>
<p>
Have you ever implemented a Map where each key could be associated to a list of values - that's exactly what a Multimap is. This is useful in many cases, for example indexing. To show the functionality I'll index fruits by colors. The <i>Fruit</i> class is just a class with a name and a color and the fruits collection contains banana, strawberry, cucumber, kiwifruit, tomato and lemon. First we create a new multimap for the color index, then we look through all the fruits and add them to the color index using the color of the fruit as index. After we have constructed the index, we get a collection of red fruits using the <i>get</i> method. And finally, we assert that a tomato is a red fruit.
</p>
<pre class="java">&nbsp;
Multimap&lt;Color, Fruit&gt; colorIndex = HashMultimap.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>Fruit fruit : fruits<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    colorIndex.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>fruit.<span style="color: #006600;">getColor</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, fruit<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
Collection&lt;Fruit&gt; redFruits = colorIndex.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AColor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Color</span></a>.<span style="color: #006600;">RED</span><span style="color: #66cc66;">&#41;</span>;
assertTrue<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Tomato is a red fruit&quot;</span>, redFruits.<span style="color: #006600;">contains</span><span style="color: #66cc66;">&#40;</span>TOMATO<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>BiMap</h4>
<p>
A <i>BiMap</i> is an implementation of a bidirectional map, that is a map where a one-to-one relation between each key and value exists. The <i>BiMap</i> is special because it is capable of producing the inverse mapping using the <i>inverse</i> method. Bidirectional maps are also useful for indexing in cases where an one-to-one relationship exists and you don't want the relationship encoded in the objects. As an example we will look at mapping numbers to their names and back again.
</p>
<pre class="java">&nbsp;
ImmutableBiMap&lt;Integer, String&gt; biMap = ImmutableBiMap.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #ff0000;">&quot;Zero&quot;</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #ff0000;">&quot;One&quot;</span>,
        <span style="color: #cc66cc;">2</span>, <span style="color: #ff0000;">&quot;Two&quot;</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #ff0000;">&quot;Three&quot;</span><span style="color: #66cc66;">&#41;</span>;
assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;2 should be mapped to Two&quot;</span>, <span style="color: #ff0000;">&quot;Two&quot;</span> , biMap.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
We can easily create a mapping between the numbers and their names using the <i>of</i> method on the <i>ImmutableBiMap</i> implementation. As with the <i>Multisets</i> and <i>Multimaps</i> numerous implementations exists to fit your exact needs.
</p>
<p>
For a <i>BiMap</i> we can get the inverse <i>BiMap</i> the following way:
</p>
<pre class="java">&nbsp;
BiMap&lt;String, Integer&gt; inverseBiMap = biMap.<span style="color: #006600;">inverse</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Two should be mapped to 2&quot;</span>, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a>.<span style="color: #006600;">valueOf</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>,
        inverseBiMap.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Two&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Ordering</h3>
<p>
If you ever have struggled with implementing Java's <i>Comparator</i> interface the <i>Ordering</i> class from Google Collections is you friend. The <i>Ordering</i> class provides you with everything you need for handling ordering of collections. Furthermore the <i>Ordering</i> class implements the <i>Comparator</i> interface to handle backwards compatibility. If you, for example, want to sort the fruits earlier mentioned first by color then by name it can be done the following way.
</p>
<pre class="java">&nbsp;
Function&lt;Fruit, Color&gt; getColorFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Fruit, Color&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AColor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Color</span></a> apply<span style="color: #66cc66;">&#40;</span>Fruit from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from.<span style="color: #006600;">getColor</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Function&lt;Fruit, String&gt; getNameFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Fruit, String&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> apply<span style="color: #66cc66;">&#40;</span>Fruit from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Ordering&lt;Fruit&gt; colorOrdering = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">onResultOf</span><span style="color: #66cc66;">&#40;</span>getColorFunction<span style="color: #66cc66;">&#41;</span>;
Ordering&lt;Fruit&gt; nameOrdering = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">onResultOf</span><span style="color: #66cc66;">&#40;</span>getNameFunction<span style="color: #66cc66;">&#41;</span>;
&nbsp;
Ordering&lt;Fruit&gt; colorAndNameOrdering = colorOrdering.<span style="color: #006600;">compound</span><span style="color: #66cc66;">&#40;</span>nameOrdering<span style="color: #66cc66;">&#41;</span>;
&nbsp;
ImmutableSortedSet&lt;Fruit&gt; sortedFruits = ImmutableSortedSet.<span style="color: #006600;">orderedBy</span><span style="color: #66cc66;">&#40;</span>
        colorAndNameOrdering<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addAll</span><span style="color: #66cc66;">&#40;</span>fruits<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">build</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>Joiner.<span style="color: #006600;">on</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;, &quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">join</span><span style="color: #66cc66;">&#40;</span>sortedFruits<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
Prints out:</p>
<pre>
Green Cucumber, Green Kiwifruit, Red Strawberry, Red Tomato, Yellow Banana,
Yellow Lemon
</pre>
</p>
<p>
First I create the ordering of fruits by color. The <i>Color</i> enumeration implements <i>Comparable</i>, so we just want to promote the ordering of fruits to use the natural order of the <i>Color</i> class. To do this we create a natural order on the result of the function that retrieves the color from a fruit. To verify that the ordering works, I create a new <i>ImmutableSortedSet</i> with the ordering we just created and print the result. Notice that it is necessary to used the <a href="http://en.wikipedia.org/wiki/Builder_pattern" title="Builder pattern">builder pattern</a> in order to create the <i>ImmutableSortedSet</i> with a specified order.
</p>
<p>
The ordering on fruit names is similar to the way we order by  colors except we use a function that retrieves the name of the fruit.
</p>
<p>
When we have the two orderings we can make a compound ordering by using the <i>compound</i> method on the ordering that should be applied first. A compound ordering applies each ordering in turn to achieve a hierarchical ordering. In this case the color-ordering is first applied, if the objects are equal, according to that ordering, the naming-ordering is applied.
</p>
<p>
Another use case of the <i>Ordering</i> class is sorting <i>Iterable</i> classes where elements are not guaranteed to be unique. Normally you would have to first convert the iterable to a list and then use the <i>sort</i> method on the <i>Collections</i> class to sort the elements. Consider the case of sorting an iterable of numbers in reverse order, this can be done the following way in standard Java:
</p>
<pre class="java">&nbsp;
List&lt;Integer&gt; sortedNumbers = <span style="color: #000000; font-weight: bold;">new</span> ArrayList&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span>numberIterable<span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">sort</span><span style="color: #66cc66;">&#40;</span>sortedNumbers, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">reverseOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
The same result can be achieved with Google Collections the following way:
</p>
<pre class="java">&nbsp;
List&lt;Integer&gt; sortedNumbers = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">reverse</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">sortedCopy</span><span style="color: #66cc66;">&#40;</span>numberIterable<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
This doesn't seem like a big difference. But in the standard Java example involves three different classes and the generics is specified two times.
</p>
<h3>Iterables and Iterators</h3>
<p>
Iterables and iterators are a powerful abstraction that lets you handle streams of data in an uniform way. But the standard Java library doesn't provide you with  many tools to handle these types. Google Collections includes two classes with several convenience methods to work on these types. The two classes contains the  same methods so I'll only focus on iterables.
</p>
<p>
Imagine that you are given an iterable of numbers should find all the even numbers, square them and return a new iterable of the result. Of course this should be done  without reading all the numbers in the given iterable. In standard Java you would need to implement two iterators and two iterables in order to achieve this. In  Google Collection it can be done the following way:
</p>
<pre class="java">&nbsp;
Predicate&lt;Integer&gt; evenPredicate = <span style="color: #000000; font-weight: bold;">new</span> Predicate&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> apply<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> input<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> input % <span style="color: #cc66cc;">2</span> == <span style="color: #cc66cc;">0</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Iterable&lt;Integer&gt; evenNumbers = Iterables.<span style="color: #006600;">filter</span><span style="color: #66cc66;">&#40;</span>numbers, evenPredicate<span style="color: #66cc66;">&#41;</span>;
&nbsp;
Function&lt;Integer, Integer&gt; squareFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Integer, Integer&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> apply<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from * from;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Iterable&lt;Integer&gt; squareOfEvenNumbers = Iterables.<span style="color: #006600;">transform</span><span style="color: #66cc66;">&#40;</span>evenNumbers,
        squareFunction<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
First we create a predicate function that only accepts even numbers and filters the given numbers by this predicate function. Notice this is done lazily so the original iterable is not touched, which means at no time is a collection containing all the results constructed and stored in memory. All the methods on <i>Iterables</i> and <i>Iterators</i> classes is as lazy as possible.
</p>
<p>
Then we create a <i>square</i> function and apply it to the iterable of even numbers giving us a new iterable with the squared even numbers.
</p>
<p>
It is important to understand that the predicate and <i>square</i> functions will first be applied when the iterable is used to iterate through the squared even numbers.
</p>
<h3>Conclusion</h3>
<p>
In my opinion Google Collection will definitely improve your code, making it more readable and save you from creating your own error-prone implementation of the functionality already provided and tested by Google. I think that it is especially good that the library extends the standard library in a non intrusive way, instead of creating a parallel collection library. This also means that you can choose to use only the convenience classes and not spreading Google specific types all over your system if that worries you.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/22/google-collections/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
