Here's a handy utility called “DynamicComparer”, that will dynamically sort an array or ArrayList on multiple fields, in ascending or descending order, without or without case sensitivity.
Using this, it is no longer necessary to allow sorting by having classes implement the Comparable interface, or writing custom Comparators for each business class.
I welcome feedback! Let me know if you think of any improvements.
--Kamilche
Code here, in filename DynamicComparer.java
JUnittest here, in filename DynamicComparer_Test.java
This message was edited 1 time. Last update was at by Cindy Carney
Bear Bibeault
Author and opinionated walrus
Marshal
That is a big difference and to much in most cases.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Cindy Carney
Ranch Hand
Joined: Jan 12, 2010
Posts: 57
posted
0
Thanks for the feedback. You got that error is because the field is not public - comparators can only access public fields.
You were spot on about the speed, though! Wow, it's abysmal - 20 to 70x slower than a normal comparator. I added a 'testCapacity' routine to the JUnit tests, and discovered what you meant.
I tried some different methods, and came up with this one. It is flexible, in that it will let you sort on multiple columns with different sort criteria, like DynamicComparer... but it performs much faster, and scales well. It also allows you to access private fields.
It's still slower than a custom comparator, so if you have a need for a one off fast sort, hand coding is probably the best way to go. This routine is mainly useful for small arrays, such as you might use during web development, when you're presenting a limited result set to the user, letting them choose their sort columns, and don't want to have to hit the database every time they click the sort button.
Give this one a whirl, I think you'll like it better. My timings are below:
Standard method: Sorted 100000 items in 47 milliseconds. This is the usual Java method, where you create a new custom comparator for each sort you want.
New method: Sorted 100000 items in 172 milliseconds. This is the new method I created, which uses a single custom comparator that handles all possible sorts you might want, with per-field direction and case sensitivity.
Lazy method: Sorted 100000 items in 3437 milliseconds. This method is like 'new', but calls a pre-done compareTo proc to get you out of handing-coding the compareTo proc. The pre-done compareTo proc uses reflection to look up the fields, so while it saves you coding work, this is the slowest method.
File MultiComparable.java
File MultiComparer.java
File TestClass.java
File MultiComparable_Test.java
subject: CODE: Dynamic Sorting on Multiple Indexes