Tuesday, August 15, 2006

Sorting objects in a Java collection

We all have felt the need to sort our custom objects based on the value of ainstance varaible of that object..For e.g. sorting of a Vector of AddressCard objects according to theDisplayName.i.e Consider the following class:
class AddressCard{ public String sDisplayName; // Other instance variables.}

Now say we want to sort a Vector of AddressCard objects according to the valueof sDisplayName.Though we can write a custom sorting mechanism for this, we have another neatsolution which requires miminal coding.We make use of the TreeMap object as follows, which is sorted internally..Given below is the code snippet.

//Instantiate a TreeMap object....If Case sensitive is desired, use a emptyconstructor.
TreeMap tMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);

//keep on adding the object's field (to be sorted) as the key and the object reference as the value.
for loop:
tMap.put(sDisplayName, AddressCardObject);
//-------------------end of for loop

Once all the objects have been entered into the TreeMap, they are sorted automatically..So if U want the sorted Vector ofobjects then just do the following:
Collection c = tMap.values();
Vector v = new Vector(c); //Pass the collection in the constructor.

And Voila !!!....we have a sorted Vector of objects sorted according to therequired field...and that too in just 4-5 lines of code.

No comments:

Post a Comment