zoukankan      html  css  js  c++  java
  • Java Map 排序

    1. 按照key值排序

      对于java中Map的排序,有排序Map,比如TreeMap,对于这个Map,首先只能按照键排序,其次再put和remove的时候由于需要排序,性能上会有所牺牲。
      这种方案,使用hashmap进行创建和添加,如果需要按照key排序,则可以将该hashmap作为参数传递到new TreeMap(hashmap),则可以完成按照key的排序。

      

    TreeMap treemap = new TreeMap(hashmap);

    2. 按照value值排序

      使用TreeMap,用List封装,然后添加比较器,进行排序

      

    List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(treemap.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {   
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {   
                    return (o2.getValue() - o1.getValue());   
                }   
    });

       此为降序,升序交换o2,o1位置即可。

      当然比较器按照个人需求写。这只是简单的key是string,然后按照拼音排序,value是int,按照大小排序。

  • 相关阅读:
    Plug It In
    The King's Walk
    Water Testing 匹克定理
    基尔霍夫矩阵
    nginx 常用的命令
    Nginx window安装
    使用nrm管理 npm 镜像仓库
    window 安装node.js
    变量和数据类型
    同步,异步,阻塞,非阻塞
  • 原文地址:https://www.cnblogs.com/lijc1990/p/3510898.html
Copyright © 2011-2022 走看看