I have a requirement to sort a collection of objects, They are shown on a web page in tabular format. My sorted collection is created like
TreeSet<MyObject> objs= new TreeSet<MyObject>();
Currently MyObject is implementing Comparable interface to provide sorting. In the compareTo method object is checked against the date of creation as my sorting logic.
Now I have got a requirement to sort this collection on the basis of various other instance variable of the class. After exploring options to achieve this I have got two ideas for this execution,
- Use a
Comparator. In this class I can implement my logic to sort the collection. - Create a database query to return the sorted collection for
MyObject. I can useORDER BYOptimization to achieve this.
So, I would like to know your opinion on the both approaches and what should be best optimum solution for such a requirement.
If you already have the objects in memory, then sorting them with a
Comparatoris definitely faster.If you query them from the DB each time anyway, then using
ORDER BYis definitely easier and probably faster as well.