java 想排序鍵值對的方法


第一種,就是對鍵進行排序,這個時候用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排序
  }
})




還有一種方法就是構造一個優先隊列,待填坑



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM