Wednesday, March 18, 2009

Sort Objects of ArrayList

We use ArrayList many times to store list of Objects.
How to Sort records of ArrayList of objects using Collections.sort method based on particular field.

Suppose we have Class Employee as :

public class Employee {

private String empName;
private String empDept;
private double salary;

public String getEmpDept() {
return empDept;
}
public void setEmpDept(String empDept) {
this.empDept = empDept;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

main method to demonstrate sorting of ArrayList which contains few Employees.

eg:
public static void main(String[] args) {

ArrayList empList = new ArrayList();
Employee e1 = new Employee();
e1.setEmpName("Abcd");
e1.setEmpDept("ACCT");
Employee e2 = new Employee();
e2.setEmpName("Ssss");
e2.setEmpDept("HRD");
Employee e3 = new Employee();
e3.setEmpName("rrrr");
e3.setEmpDept("MKTG");
Employee e4 = new Employee();
e4.setEmpName("bbbb");
e4.setEmpDept("ACCT");
Employee e5 = new Employee();
e5.setEmpName("mmmm");
e5.setEmpDept("DEVP");
empList.add(e1);
empList.add(e2);
empList.add(e3);
empList.add(e4);
empList.add(e5);
System.out.println("Before Sorting:");
for (Employee employee : empList) {
System.out.println("Employee :"+employee.getEmpName());
}

Collections.sort(empList, new Comparator(){
public int compare(Object obj1, Object obj2) {
Employee emp1 = (Employee) obj1;
Employee emp2 = (Employee) obj2;
return emp1.getEmpName().compareToIgnoreCase(emp2.getEmpName());
}
});
System.out.println("");
System.out.println("After Sorting:");
for (Employee employee : empList) {
System.out.println("Employee :"+employee.getEmpName());
}

}

Output is:
Before Sorting:
Employee :Abcd
Employee :Ssss
Employee :rrrr
Employee :bbbb
Employee :mmmm

After Sorting:
Employee :Abcd
Employee :bbbb
Employee :mmmm
Employee :rrrr
Employee :Ssss

No comments: