import java.util.Comparator;import org.apache.commons.beanutils.PropertyUtils;public class PropertyComparator implements Comparator{private String propertyName;
public PropertyComparator(String property){this.propertyName = property;}
public int compare(Object object1, Object object2){int result = 0;
try{Object property1 = PropertyUtils.getProperty(object1, propertyName);Object property2 = PropertyUtils.getProperty(object2, propertyName);if (property1 instanceof Comparable){result = ((Comparable)property1).compareTo(property2);}
}catch (Exception e){e.printStackTrace();
}return result ;}
Ok now moving on to usage of this class, Say we have a class called Employee
which is defined like:
public class Employee{
String empId;
String empName;
public Employee(String empId,String empName)
{
this.empId = empId;
this.empName = empName;
}
public String getEmpId()
{
return empId;
}
public void setEmpId(String empId)
{
this.empId = empId;
}
public String getEmpName()
{
return empName;
}
public void setEmpName(String name)
{
this.empName = name;
}
public String toString()
{
return "EmpId : "+empId+" EmpName : "+empName;
}
}
Ok i must tell you that if you dont have getter and setter methods for the properties , this will not work.
Now moving on
public class TestGenericComparator
{
public static void main(String args[])
{
Employee emp1 = new Employee("1","Zebra");
Employee emp2 = new Employee("2","Apple");
ListempList = new ArrayList ();
empList.add(emp1);
empList.add(emp2);
........................
Collections.sort(empList,new PropertyCoparator("empName"));
for(Employee emp:empList)
{
System.out.println(emp.toString());
}
}
}
Well this concept can be similarly extended for multi property comparators.
2 comments:
Spring already has one of these (PropertyComparator) so you don't need to write your own. You can chain them together using commons-collection ComparatorChain to support multi-property comparisons.
Don't write a "main method". Write an unit test. :-)
Kind Regards
Post a Comment