Monday, September 24, 2012

Sorting a bean List with Commons

Nowadays whenever I surf the net, comparable interface is widely used to sort a List of objects. I am very sure it's the best approach, no doubt in that :)

However, if you want to sort in more than one place of your projects, I feel the code will be redundant. Am I right?

The alternate and the best solution is to use the Apache Commons Bean Utils


And this is how I did it:

Asceding order:
For ascending order, we should give the parameter alone. For instance, if we want sort by “endDate”. We should pass the parameter endDate to the BeanComparator class instance.


Reverse Order Sorting(Descending Order):
For descending order, we should give the parameter along with the instance of ReverseComparator class. For instance, if we want to sort by “firstName”. We should pass two parameters, such as the endDate and the instance of ReverseComparator class to the BeanComparator class.


Note:
Just keep in mind that your fild must be NON-NULL otherwise you'll get a pretty NPEx slap in your face.

No comments:

Post a Comment