If we want to sort Objects in an ArraList based on any particular field(s) then we need to implement the Comparator interface and override the compare method.
For Example :
I have a class called Employee.
public class Employee {
private String empName;
private int empId;
public String empLocation;
/**
* @return the empName
*/
public String getEmpName() {
return empName;
}
/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}
/**
* @return the empId
*/
public int getEmpId() {
return empId;
}
/**
* @param empId the empId to set
*/
public void setEmpId(int empId) {
this.empId = empId;
}
/**
* @return the empLocation
*/
public String getEmpLocation() {
return empLocation;
}
/**
* @param empLocation the empLocation to set
*/
public void setEmpLocation(String empLocation) {
this.empLocation = empLocation;
}
}
Sorting :
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
*/
/**
* @author ADMIN
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Employee e1 = new Employee("Baskar",1,"Chennai");
Employee e2 = new Employee("Vinay",2,"Chennai");
Employee e3 = new Employee("Mani",3,"Chennai");
Employee e4 = new Employee("Raj",4,"Chennai");
ListemployeeList = new ArrayList ();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
System.out.println("List before sorting "+employeeList.toString());
Collections.sort(employeeList, new Comparator(){
public int compare(Object o1, Object o2) {
Employee e1 = (Employee) o1;
Employee e2 = (Employee) o2;
return e1.getEmpName().compareToIgnoreCase(e2.getEmpName());
}
});
System.out.println("List after sorting "+employeeList.toString());
}
}
Result :
List before sorting [Baskar -- 1 -- Chennai, Vinay -- 2 -- Chennai, Mani -- 3 -- Chennai, Raj -- 4 -- Chennai]
List after sorting [Baskar -- 1 -- Chennai, Mani -- 3 -- Chennai, Raj -- 4 -- Chennai, Vinay -- 2 -- Chennai]
No comments:
Post a Comment