我有此代碼來填充HashMap
並將它傳遞到TreeMap
以Key
值自然排序它。使用HashMap並使用具有遞減鍵值的TreeMap進行排序
Map<Integer, String[]> hashMap = new HashMap<Integer, String[]>();
hashMap.put(3, new String[]{"1","2"});
hashMap.put(2, new String[]{"1","2"});
hashMap.put(4, new String[]{"1","2"});
hashMap.put(1, new String[]{"1","2"});
System.out.println(hashMap);
Map<Integer, String[]> treeMap = new TreeMap<Integer, String[]>(hashMap);
System.out.println(hashMap); // Natural Order, Ascending
現在我的問題是,如何將我的treeMap
在Descending
順序排序?我準備了名爲KeyComparator
的比較器類,按Key
的降序排列。這裏是我下面的代碼:
public class KeyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) {
return 1;
} else if (o1 > o2) {
return -1;
} else {
return 0;
}
}
}
的TreeMap
沒有2參數的構造函數例如像TreeMap(new KeyComparator(),hashMap)
。如何在同一時間使用我的KeyComparator
課程將hashMap
加載到我的treeMap
中。
如果你需要的是下降的自然順序,那麼你可以使用'新的TreeMap(hashMap).descendingMap()' –