Sorting Lists in Apex

Salesforce.com’s Apex programming language has a lot of nice features, especially for being relatively new to the scene. It has a good amount of functionality and the Force.com platform makes it easy to quickly develop applications. However, there are some features that I would like to see implemented. One of those features is being able to easily sort a list of complex data types like SObjects or ListOptions.

If you have a list of integers, strings, or other primitive data types, sorting is easy enough, simply call listName.sort(). The method will sort the list in ascending order for you. The problem comes in when you need to sort a more complex data type. For example, if you need to sort a list of SelectOptions to be used in a Visualforce page select list, the sort() method will not work. For this we need to write our own method. Since this is something we have dealt with frequently in our Force.com development projects, one of my colleagues decided to write a simple class for it, and I decided to pass it on. 

The attached class below is a simple sort that iterates through a list of SelectOptions and sorts by label. It could easily be adapted to sort SObject data types too, on whichever field you like. Until the native sort methods in Apex can handle complex data types, I’ll be adding this class to all my projects that require advanced sorting.

QuickSort Class

Comments

Be the first to comment!

Leave A Comment

Please help us stop spam by typing the word you see in the image below: