views:

122

answers:

1

Hi,

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,

  1. Use a Comparator. In this class I can implement my logic to sort the collection.
  2. Create a database query to return the sorted collection for MyObject. I can use ORDER BY Optimization 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.

+9  A: 

If you already have the objects in memory, then sorting them with a Comparator is definitely faster.

If you query them from the DB each time anyway, then using ORDER BY is definitely easier and probably faster as well.

Joachim Sauer
@Joachim Sauer +1 w00w very nice and yet so simple answer
c0mrade