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
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.
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.
SortedSet is an interface. It maintains an ordered set of elements. TreeSet is an implementation of SortedSet.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With