Treeset to order elements in descending order

心已入冬 提交于 2019-11-28 08:55:32

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.

Brian

TreeSet::descendingSet

In Java 6 and later, there is a method on TreeSet called descendingSet() producing a NavigableSet interface object.

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
Pierre
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 ?

Ashutosh

Reverse compare

You can reverse the order of the two arguments in the compare method of your Comparator.

TreeSet t = new TreeSet(new MyComparator());
  {
class MyComparator implements Comparator
{
  public int compare(Integer i1,Integer i2)
        {
         Integer I1=(Integer)i1;
         Integer I2=(Integer)i2;
         return I2.compareTo(I1);  // return -I1compareTo(I2);
        }
}
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!