Java / Android Sort ArrayList

How to sort an ArrayList in Android:

Following code is describing, how to sort an Android / Java array list of user defined class.

Collections.sort(empList, new Comparator<Employee>(){
              public int compare(Employee emp1, Employee emp2) {
                return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
              }
            });

Below is complete example to sort array list:

[sociallocker]

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<Employee> empList=new ArrayList<Main.Employee>();
        Employee emp=new Employee();
        //Add first employee
        emp.setId(1);
        emp.setFirstName("xyz");
        empList.add(emp);

        //Add second employee
        emp=new Employee();
        emp.setId(2);
        emp.setFirstName("wjx");
        empList.add(emp);

        //Add third employee
        emp=new Employee();
        emp.setId(3);
        emp.setFirstName("bce");
        empList.add(emp);
        
        Collections.sort(empList, new Comparator<Employee>(){
              public int compare(Employee emp1, Employee emp2) {
                return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
              }
            });
        
        //empList is in sorted form by firstName

}  

public class Employee {
        int _id;
        String _firstName;

        public int getId() {
            return _id;
        }

        public void setId(int id) {
            _id = id;
        }

        public String getFirstName() {
            return _firstName;
        }

        public void setFirstName(String firstName) {
            _firstName = firstName;
        }
    }

}

[/sociallocker]

Leave a comment

Your email address will not be published. Required fields are marked *