Writing Comparator for sorting on columns
By Angsuman Chakraborty, Gaea News NetworkSunday, January 25, 2004
The challenge is to write a generic comparator which allows for sorting of the data based on a chosen column in either ascending or descending order when the column data type is not known upfront.
When I faced with providing the ability to sort based on columns, I realized I had to implement a comparator which based on sorting criteria can sort in either ascending or descending order. Also the data type of the columns can be different. So if I write a comparator for String, it will not work for Integer field. However as I did not know the data type of the column beforehand, I had to create something generic which worked everywhere. And my constant strive to create something simple.
Here’s what I came up with:
class Comp implements Comparator{
int rvalue;
String cf;
Boolean corder;
public Comp(String compfld,Boolean order){
cf = compfld;
corder = order;
}
public int compare(Object first, Object second){
try {
Comparable cFirst = null, cSecond = null;
cFirst = (Comparable) first.getClass().getField(cf).get(first);
cSecond = (Comparable) second.getClass().getField(cf).get(second);
return (corder.booleanValue())?cFirst.compareTo(cSecond):cSecond.compareTo(cFirst);
} catch(Exception e) {
throw new RuntimeException("Invalid object passed");
}
}
}
This Comparator is passed on the field/column name to compare, as a string, and it fetches the column information from the object and compares with the corresponding information from the other object. Here as you can see each object instance contains all the information for a row of data. So one row maps to one object instance.
|
August 27, 2009: 11:42 am
Hi, I am getting the below warings when i use the above peace of code. ^ Can you please help us ? |
|
Arun |
|
Omar Malik |
January 7, 2008: 8:08 am
Hi I am trying to implement the code you sent. Can you please show me how I would call Coolections.sort method using the comparator you wrote above. I have a value object with fields and getter and setter methods called ProductVO. I just want to sort an ArrayList of ProductVO based on one of its fields called lastname. However I dont want to write a comparator specific to the ProductVO but use your comparator to sort any type of array list of VOs. |
Arun