Pages

Monday, January 10, 2011

Sorting the objects using collections

We can implement using two following ways:

Way 1:
Step 1:
the object which supposed to sort in collection needs to be implements Comparable interface
For Ex: Object TestPOJO needs to be sort so that class looks like below:


public class TestPOJO implements Comparable
{
int id;
String code;
TestPOJO(int a, String b){
this.id=a;
this.code=b;
}
………..
Getters/setters…
}
Step 2: below this for Ascending order
Override the compareTo method
public int compareTo(Object obj)
{
int retVal = 0;
TestPOJO testPojo1 = (TestPOJO)obj;
if(testPojo1!=null )
{
if((testPojo1!= null) && (this.getCode() != null))
{
retVal = this.getCode().compareTo(testPojo1.getCode());
}
}
return retVal;
}
Step 3:
The Main Class where you are sorting the list of objects:
List testPOJOList = new ArrayList();
TestPOJO obj1 = new TestPOJO(1,”SBI”);
TestPOJO obj2 = new TestPOJO(1,”ABN AMRO”);
TestPOJO obj3 = new TestPOJO(1,”ANB”);
TestPOJO obj4 = new TestPOJO(1,”KVB”);
TestPOJO obj5 = new TestPOJO(1,”SYN”);
TestPOJO obj6 = new TestPOJO(1,”SCB”);

testPOJOList.add(obj1);
testPOJOList.add(obj2);
testPOJOList.add(obj3);
testPOJOList.add(obj4);
testPOJOList.add(obj5);
testPOJOList.add(obj6);

if((testPOJOList!= null) && (testPOJOList.size() > 0))
{
Collections.sort(testPOJOList);
}

Way2:
Using anonymous class
For this way of implementation as in above step1, step 2: not required here.

For Ex: Object TestPOJO needs to be sort so that class looks like below:
No need to implement comparable interface here.
public class TestPOJO
{
int id;
String code;
TestPOJO(int a, String b){
this.id=a;
this.code=b;
}
………..
Getters/setters…
}
Here we need to pass the Comparator object to the Collections.sort method and override the compare(obj,obj) method like below:
Collections.sort(testPOJOList, new Comparator()
{
public int compare(Object o1, Object o2)
{
TestPOJO test1 = (TestPOJO) o1;
TestPOJO test2 = (TestPOJO) o2;

String d1 = (String) test1.getCode(); /////// line A
String d2 = (String) test2.getCode; /////// line B
return d1.compareTo(d2); ///////////// line C
}
}
);
In above way also we can use the first way:
Just replace the line A, Line B, Line c with below line
return test1.compareTo(test2);
And TestPOJO class should be implements Comparable interface and must override the compareTo(object) method.

No comments:

Post a Comment