Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the order of SortedSet

I want to print an ordered list in Map using the following:

Map<Float, String> mylist = new HashMap<>();

mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);

SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet());

for (Float i : orderlist) {
    System.out.println(i+" "+mylist.get(i));
}

The above code prints:

5.1 c
10.5 a
12.3 b    

But how do I the print the orderlist in reverse order like below:

12.3 b
10.5 a
5.1 c
like image 719
user2109581 Avatar asked Feb 01 '16 03:02

user2109581


People also ask

Is SortedSet ordered?

Interface SortedSet<E> A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order.

How does TreeSet maintain descending order?

The TreeSet uses a TreeMap internally for storing data. By default, the objects or elements of the TreeSet are stored according to the natural ordering in ascending order. The TreeSet class that implements TreeSet in Java implements the 'NavigableSet' interface and also inherits AbstractSet class.

What is difference between SortedSet and TreeSet?

SortedSet is an interface. It maintains an ordered set of elements. TreeSet is an implementation of SortedSet.


1 Answers

If you're willing to store the elements in the SortedSet in reverse order, the only change you need to make is to construct the TreeSet with an appropriate constructor which takes a custom Comparator:

Map<Float, String> mylist = new HashMap<>();

mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);

SortedSet<Float> orderlist = new TreeSet<Float>(Collections.reverseOrder());
orderList.addAll(mylist.keySet());

for (Float i : orderlist) {
    System.out.println(i+" "+mylist.get(i));
}

Note the neat method here is Collections.reverseOrder() which returns a Comparator which compares in the opposite of the natural ordering of elements.

like image 51
augray Avatar answered Oct 26 '22 13:10

augray