Quick Java Object Comparing and Sorting

Object comparison can be done two ways. Either implementing the Comparable interface and allowing a sort to sort the objects, or create your own comparators.

Implementing the Comparable interface locks that object to only compare in one way. Many cases occur when sorting by different criteria is a requirement.

Implementing the Comparator interface can be time consuming since each comparison needs a new comparator classes to be created. You can quickly grow the amount of classes in your project just by the sorting requirements alone!

Apache Commons has a great solution to drastically reduce code of the sort.
The BeanComparator uses reflection to sort the list. You are able to sort by the variables within the objects.

Collections.sort(people, new BeanComparator("lastname"));

You can also sort multiple fields by chaining

ComparatorChain comparatorChain = new ComparatorChain();
comparatorChain.addComparator(new BeanComparator("lastName"));
comparatorChain.addComparator(new BeanComparator("firstName"));
comparatorChain.addComparator(new BeanComparator("age"));
Arrays.sort(people, comparatorChain );

I would like to see the varags Java language feature available to this soon. You wouldn't even need the chain.

If the below was part of the Collections API

sort(List list, Comparator... c) 

Then all you would need to chain would be just like below. Same as above, just a little thinner and cleaner.

Collections.sort(people, new BeanComparator("lastname"), 
new BeanComparator("firstName"), new BeanComparator("age"));

Post new comment

Subscribe to Syndicate