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.
Any hint or help will be greatly appreciated.
Yours,
Frustrated.
1.)
Util.java:
import java.util.*;
public class Util
{
public static List<Employee> getEmployees()
{
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(new Integer(5),"Frank",28));
col.add(new Employee(new Integer(1), "Jorge", 19));
col.add(new Employee(new Integer(6), "Bill", 34));
col.add(new Employee(new Integer(3), "Michel", 10));
col.add(new Employee(new Integer(7), "Simpson", 8));
col.add(new Employee(new Integer(4), "Clerk",16 ));
col.add(new Employee(new Integer(8), "Lee", 40));
col.add(new Employee(new Integer(2), "Mark", 30));
return col;
}
}
2.)
testEmployeeSortSortByEmpIdThanByName.java:
import java.util.Collections;
import java.util.List;
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);
}
private static void printList(List<Employee> list)
{
System.out.println("EmpId\tName\tAge");
for (Employee e:list)
{
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
3.)
EmpSortByEmpId.java:
import java.util.Comparator;
public class EmpSortByEmpId implements Comparator<Employee>
{
public int compare(Employee o1, Employee o2)
{
return o1.getEmpId().compareTo(o2.getEmpId());
}
}
4.)
EmpSortByName.java:
import java.util.Comparator;
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;
}
}