Wednesday, July 29, 2009

Sorting a vector of objects using Comparator

Here is something really cool about sorting a Vector of objects. At least it is appealing to me. Let say we have a vector of "Students" objects and we are interested to sort the objects using one of its private fields, say, "StudentID" which is of data type Integer.

The code is as follow:

public static void anyMethod(){
try {
Collections.sort(yourVectorThatContainsObjects, ComparatorName);
} catch (Exception ex) {}
}

public static Comparator<Object> ComparatorName = new Comparator<Object>() {
public int compare(Object resultItem1, Object resultItem2) {
Integer id1 = ((Students)resultItem1).StudentID;
Integer id2 = ((Students)resultItem2).StudentID;
return id2.compareTo(id1);
}
};
The result of this sort is in descending order, eg largest to smallest. However there is a simple trick to sort it in an ascending order. Simply use "return id1.compareTo(id2);" It works for me. I hope it works for you too. Otherwise, please feel free to leave a comment so that I can investigate my code :)

0 comments:

Post a Comment