use*_*581 8 java sortedset treeset
我想使用以下内容在Map中打印一个有序列表:
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));
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
5.1 c
10.5 a
12.3 b
Run Code Online (Sandbox Code Playgroud)
但是如何以相反的顺序打印订单列表,如下所示:
12.3 b
10.5 a
5.1 c
Run Code Online (Sandbox Code Playgroud)
如果您愿意以SortedSet相反的顺序存储元素,那么您需要做的唯一更改是TreeSet使用适当的构造函数构造它,该构造函数采用自定义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));
}
Run Code Online (Sandbox Code Playgroud)
注意这里的整洁方法是Collections.reverseOrder()返回一个Comparator与元素的自然顺序相反的方法.
小智 5
您也可以尝试以下方法:
Map<Float, String> mylist = new HashMap<Float, String>();
mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);
SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet()).descendingSet();
for (Float i : orderlist) {
System.out.println(i+" "+mylist.get(i));
}
Run Code Online (Sandbox Code Playgroud)
尝试使用NavigableSet:
public NavigableSet<E> descendingSet()
Run Code Online (Sandbox Code Playgroud)
像这样:
SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet());
SortedSet<Float> treereverse = new TreeSet<Float>();
// creating reverse set
treereverse=(TreeSet)orderlist.descendingSet();
Run Code Online (Sandbox Code Playgroud)
最后你得到了treereverse相反的顺序。