Thursday October 20, 2005 | ${log.root}/lowem.log Inflation, Investing and Everything |
|
Biow was asking for a way to dynamically sort an ArrayList of bean objects. The beans are your typical JavaBeans with private attributes and getter/setter methods for each attribute. The JDK Collections.sort() method provides for a custom Comparator that you can implement yourself, but it gets tedious very quickly to have to write a bunch of Comparators to sort each field and also having to take into account ascending/descending order. I had something in mind about using reflection to dynamically invoke the getter method, and then getting the values, and putting that to work in a custom Comparator, but of course someone must have encountered the same problem before. York Davis has written an article on Dynamic Sorting With Java with source code for a DynamicComparator which does exactly what is needed. It accepts Collection, which is even better, which means you can throw in not only ArrayList, but also Vector and so on. (2005-10-20 11:09:28 SGT)
[Java]
Permalink
Comments [2]
Post a Comment:
Comments are closed for this entry.
Most popular blog postings on lowem.log : 1. Singapore SIBOR interest rates fall to 1.5%, lowest since Dec 2004 Featured articles on lowem.log : 1. ABC Guide to Beating Inflation in Singapore and Elsewhere |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
p.s. u want to archive the article?
Posted by biow on October 20, 2005 at 12:08 PM SGT #
To extrapolate from that, maybe the Comparator should expose a method, when given an object to be compared, look through all its getters and return a String[]. Nothing a PropertyUtils can't do. That will make it useful if you intend to allow the user to choose on the screen all the possible sorting combinations.
And since we're using PropertyUtils, how about sorting on indexed properties?
Posted by gwunwai on October 20, 2005 at 01:22 PM SGT #