Java Reference
In-Depth Information
Next, I sort the strings using the two-argument version of
Collections.sort
. The in-
teresting part is that the second argument to the
sort
method is a closure (between the
3
Closure coercion like this is discussed further in
chapter 4
.
The closure is intended to be the implementation of the
compare(String,String)
method analogous to that shown in the previous Java listing. Here I show the two dummy
arguments,
s1
and
s2
,totheleftofthearrow,andthenusethemontherightside.Iprovide
the closure as the implementation of the
Comparator
interface. If the interface had sev-
eral methods and I wanted to supply different implementations for each method, I would
provide a map with the names of the methods as the keys and the corresponding closures
as the values.
Finally,Iusetheso-called spread-dotoperatortoinvokethe
size
methodoneachelement
of the sorted collection, which returns a list of results. In this case I'm asking for the length
of each string in the collection and comparing the results to the expected values.
Bytheway,theGroovyscriptdidn'trequireanyimports,either.Javaautomatically imports
the
java.lang
package. Groovy also automatically brings in
java.util
,
java.net
,
java.io
,
groovy.lang
,
groovy.util
,
java.math.BigInteger
, and
java
.math.BigDecimal
. It's a small thing, but convenient.
Groovy Feature
Native syntax for collections and additional automatic imports reduces both the amount of
required code and its complexity.
If you've used Groovy before you probably know that there's actually an even simpler way
to do the sort. I don't need to use the
Collections
class at all. Instead, Groovy has
added a
sort
method to
java.util.Collection
itself. The default version does a
natural sort, and a one-argument version takes a closure to do the sorting. In other words,
the entire sort can be reduced to a single line:
strings.sort { -it?.size() }