Treeset to order elements in descending order

Gaurav Saini picture Gaurav Saini · Jul 7, 2009 · Viewed 58.6k times · Source

Here is the piece of code that I have used for Java 5.0

TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ;

Collections.reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated.

Is there a more optimized way of doing it?

Answer

Adamski picture Adamski · Jul 7, 2009

Why do you think this approach won't be optimized? The reverse order Comparator is simply going to be flipping the sign of the output from the actual Comparator (or output from compareTo on the Comparable objects being inserted) and I would therefore imagine it is very fast.

An alternative suggestion: Rather than change the order you store the elements in you could iterate over them in descending order using the descendingIterator() method.