第一種,就是對鍵進行排序,這個時候用map自帶的方法就行
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 降序排序
return obj2.compareTo(obj1);
}
});
構造一個treemap,這個treemap 寫一個排序規則就可以了
如果是想對值進行排序的話, 可以選擇吧把鍵值對的entry放到一個list中,進行自定義的排序(這種方法也可以按照key排序)
HashMap<Integer, Integer> map = new HashMap<>();
List<Map.entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
collections.sort(list, new comparator<Integer> {
public int compare(Map.entry<Integer, Integer> o1, Map.entry<Integer, Integer> o2) {
return o1.getValue() - o2.getValue();//正序按照value排序
return o1.getKey() - o2.getKey();//正序按照key排序
}
})
還有一種方法就是構造一個優先隊列,待填坑
