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排序
  }
})




还有一种方法就是构造一个优先队列,待填坑


原文地址:https://www.cnblogs.com/tobemaster/p/10929078.html