Friday, July 15, 2011

Sorting an ArrayList that contains pojo class

Sorting of ArrayList containing our own Class/Objects in java, Sorting ArrayList that contains customizes java class/objects in java . How to sort Arraylist that contains our own class in java?
Here is the example of sorting  a list that contains java pojo class.
In below example, we have Employee class with attribute id, first name & last name.
We have another class that actually use the sort() method of Collections which has to implement Comparator() to sort pojo with its field.

Here is the Employee Class
public class Employee 
{
    int id;
    String firstName;
    String lastName;
    
    public Employee(int id,String firstName,String lastName)
    {
        this.id=id;
        this.firstName=firstName;
        this.lastName=lastName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Here is actual class that sort the list which contains Employee objects
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class SortEmployeeList
{
    public static void main(String[] args) 
    {
        Employee emp1 = new Employee(1,"Dipen","Khadka");
        Employee emp2 = new Employee(2,"John","Rotela");
        Employee emp3 = new Employee(3,"Shark","Anderson");
        Employee emp4 = new Employee(4,"Suman","Bhatt");
        
        List<Employee> employeeList = new ArrayList<Employee>();
        employeeList.add(emp1);
        employeeList.add(emp2);
        employeeList.add(emp3);
        employeeList.add(emp4);
        
        //sort by First name
        Collections.sort(employeeList, new Comparator() {
            @Override
            public int compare(Object obj1, Object obj2) {
                Employee emp1 = (Employee)obj1;
                Employee emp2 = (Employee)obj2;
                return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
            }
        });
        //Now the employeeList is sorted based on first name
        
        
        //sort by Last name
        Collections.sort(employeeList, new Comparator() {
            @Override
            public int compare(Object obj1, Object obj2) {
                Employee emp1 = (Employee)obj1;
                Employee emp2 = (Employee)obj2;
                return emp1.getLastName().compareToIgnoreCase(emp2.getLastName());
            }
        });
        //Now the employeeList is sorted based on last name
    }
} 

2 comments: