Search code examples
javaperformancetreeset

What is the optimal way to transverse a TreeSet from last node to first in java?


I already have a solution to traverse a TreeSet. My question is related to performance, is the way I implemented the optimal one? See my code example below.

public static void main(String[] args)
{ 
  TreeSet ts = new TreeSet();
  ts.add("F");
  ts.add("B");
  ts.add("H");
  ts.add("Z");

  while (!ts.isEmpty())
  {
    String last = (String)ts.last();
    System.out.println(last);
    ts.remove(last);
  }
  // OUTPUT: Z H F B
}

Solution

  • Seems simple

        TreeSet ts = new TreeSet();
        Iterator i = ts.descendingIterator();
        while(i.hasNext()) {
            Object next = i.next();
        }
    

    or

        for(Object e : ts.descendingSet()) {
        }
    

    for Java below 1.6 you can try

        TreeSet tmp = new TreeSet(Collections.reverseOrder());
        tmp.addAll(ts);
        for(Object e : tmp) {
        }