Header Ad

Monday, April 2, 2012

Java ArrayList - Sorting List of Objects in Java

We can sort list of Objects in java using Comparators and Comparable. What are these?

Comparable is an interface that is implemented by a class of Object that have to be sorted.

java.lang.Comparable: int CompareTo(Object obj1)
This method will compare this object with obj1 object. Returns int value as follows.

1. positive - this object is greater than obj1
2. zero - this object equals to obj1
3. negative - this object is smaller than obj1

Comparator : Comparator is mainly used to override compare. Comparable will provide an ability to sort of any type of Collection.

java.util.Comparator: int compare(Object o1, Objecto2) This method compares o1 and o2 objects. Returned int value has the following meanings.

1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
The following is the Student class.

public class Student
{
int rollNo;
String name;
 
public Student(int rollNo, String name)
{
this.rollNo = rollNo;
this.name = name;
}

public void setRollNo(int rollNo)
{
this.rollNo = rollNo;
}

public int getRollNo()
{
return this.rollNo;
}
public void setName(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}
 }

The following is the "students" List collection.
Stundent std1 = new Stundent(1, "Vinay");
Stundent std2 = new Stundent(2, "Kumar");
Stundent std3 = new Stundent(3,"Goyal");
Stundent std4 = new Stundent(4,"Sharma");

ArrayList students = new ArrayList();
students.add(std1);
students.add(std2);
students.add(std3);
students.add(std4);

The following is the sample code to sort an arraylist in java.

java.util.Collections.sort(students, new Comparator<Student>()
{
    public int compare(Student std1, Student std2) {
       return std1.getName().compareToIgnoreCase(std2.getName());
    }
});