How to Use Comparator or BeanPropertyUtil to sort by multiple criteria
John Smith
Ranch Hand
Joined: Aug 21, 2004
Posts: 43
posted
0
Hi All:
I have an Employee.java class that has attributes:
id,
name
age
Is there a way to use the Java comparator to sort by age first, than with those employee with the same age sort by name and than those employees with the same name sort by Id using the comparator method in Java. Or does another has example or link to use Sun's comparator class or the BeanPropertyUtil.java class to sort based on the following above conditions.
public class testEmployeeSortSortByEmpIdThanByName
{
public static void main(String[] args)
{
List col1 = Util.getEmployees();
Collections.sort(col1,new EmpSortByEmpId());
Collections.sort(col1,new EmpSortByName());
printList(col1);
}
public class EmpSortByEmpId implements Comparator<Employee>
{
public int compare(Employee o1, Employee o2)
{
return o1.getEmpId().compareTo(o2.getEmpId());
public class EmpSortByName implements Comparator<Employee>
{
public int compare(Employee o1, Employee o2)
{
return o1.getName().compareTo(o2.getName());
}
}
5.)
Employee.java:
public class Employee implements Comparable<Employee>
{
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private Integer empId;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
private String name;
private int age;
public Employee(Integer empId, String name, int age)
{
this.empId=empId;
this.name = name;
this.age = age;
}
/*
Compare a given Employee with this object.
If employee id of this object is
greater than the received object,
then this object is greater than the other
public int
*/
public int compareTo(Employee o)
{
return this.empId - o.empId;
}
}
Ernest Friedman-Hill
author and iconoclast
Marshal
You need to write a single Comparator which compares by multiple criteria. It is indeed possible to write a generic one that uses reflection to grab the property values by name, but to solve one specific problem, it's easier to just write the single comparator; i.e.
Or you can use several Comparators in sequence, and a stable sorting algorithm (eg merge sort). Then you can sort several times on different criteria, but I think you need to do the searches in the opposite order from what you expect.
Note poor spelling: sort spelt s-e-a-r-c-h
This message was edited 1 time. Last update was at by Campbell Ritchie
subject: How to Use Comparator or BeanPropertyUtil to sort by multiple criteria