views:

713

answers:

3

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?

+8  A: 

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.

Adamski
Thanks. descendingIterator() method was introduced in 6.0 and was not there in 5.0
Gaurav Saini
+1  A: 
TreeSet<Integer> treeSetObj = new TreeSet<Integer>(new Comparator<Integer>()
  {
  public int compare(Integer i1,Integer i2)
        {
        return i2.compareTo(i1);
        }
  });

there is need to flip the result. But I guess this is just a micro-optimization... Do you really need this ?

Pierre
No, that won't be required.
Gaurav Saini
A: 

If you are using Java 6, there is a method called descendingSet().

descendingSet

public NavigableSet descendingSet()

The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa. If either set is modified while an iteration over either set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined.

    The returned set has an ordering equivalent to

Collections.reverseOrder(comparator()). The expression s.descendingSet().descendingSet() returns a view of s essentially equivalent to s.

    Specified by:
        descendingSet in interface NavigableSet<E>

    Returns:
        a reverse order view of this set
    Since:
        1.6
Brian