Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treeset to order elements in descending order

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?

like image 635
Gaurav Saini Avatar asked Jul 07 '09 08:07

Gaurav Saini


People also ask

How do you sort TreeSet in descending order in Java using comparator?

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.

Does TreeSet stores in ascending order?

Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.

How do I sort objects in TreeSet?

The TreeSet implementation is sorting by the lexicographic order of the string values you insert. If you want to sort by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator.


1 Answers

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.

like image 78
Adamski Avatar answered Sep 26 '22 00:09

Adamski