Skip to content

Instantly share code, notes, and snippets.

@cholick
Created March 13, 2012 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cholick/2029461 to your computer and use it in GitHub Desktop.
Save cholick/2029461 to your computer and use it in GitHub Desktop.
Testing apache-commons ComparatorChain
//Quick test to check the ComparatorChain in the apache-commons libraries.
@Grab(group='commons-collections', module='commons-collections', version='3.0')
@Grab(group='commons-beanutils', module='commons-beanutils', version='1.8.3')
import org.apache.commons.beanutils.BeanComparator
import org.apache.commons.collections.comparators.ComparatorChain
import org.apache.commons.collections.comparators.NullComparator
class Test {
static class SortThing implements Comparable {
String first
String last
//ComparatorChain requires collection of comparable objects
public int compareTo(Object o) {
return toString().compareTo(o == null ? "null" : o.toString())
}
public String toString() {
return "[${last}, ${first}]"
}
}
static void main(String[] args) {
def desc = false
List<SortThing> thingsToSort = [
new SortThing([last: 'A', first: '3']), new SortThing([last: 'D', first: '1']), new SortThing([last: 'B', first: '2']),
new SortThing(),
new SortThing([last: 'C', first: '5']), new SortThing([last: 'C', first: '7']), new SortThing([last: 'C', first: '6'])
] as LinkedList<SortThing>
ComparatorChain chain = new ComparatorChain()
chain.addComparator(new BeanComparator("last", new NullComparator()))
chain.addComparator(new BeanComparator("first"))
Collections.sort(thingsToSort, chain)
println thingsToSort
chain = new ComparatorChain()
chain.addComparator(new BeanComparator("first", new NullComparator()))
chain.addComparator(new BeanComparator("last"))
Collections.sort(thingsToSort, chain)
println thingsToSort
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment