Sort Multiple Fields With Collections.sort

25 03 2008

ComparatorChain chain = new ComparatorChain();
Comparator comp = new BeanComparator("firstname", new NullComparator(true));
chain.addComparator(comp,true);
comp = new BeanComparator("lastname", new NullComparator(true));
chain.addComparator(comp);
Collections.sort(customerlist,chain);

NullComparator(true) <– true places null values at the front of the list
chain.addComparator(comp,true); <– true reverse the list
customerlist = list of dynabeans


Actions

Information

One response

2 03 2009
Jon

Ah this is handy, i could only write single comparators to sort collections. Didn’t know about ComparatorChain.

Thanks,

Leave a comment