Java – how to reverse the order of sortedsets
•
Java
I want to print a sequential table in the 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)); }
Print the above code:
5.1 c 10.5 a 12.3 b
However, how to print the order list in reverse order is as follows:
12.3 b 10.5 a 5.1 c
Solution
If you want to store elements in sortedset in reverse order, the only change you need to make is to build a TreeSet using an appropriate constructor, which uses a custom comparator:
Map<Float,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 that the neat method here is collections Reverseorder(), which returns a comparator, which is the opposite of the natural order of the elements
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码