zoukankan      html  css  js  c++  java
  • [原创]Java中Map根据值(value)进行排序实现

    比如说:

    Map<String, Integer> map = new HashMap<String, Integer>();

    首先将Map集合转换成List集合,List选择ArrayList来实现:

    List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(map.entrySet());

    最后通过Collections.sort(List l, Comparator c)方法来进行排序:

    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());
        }
      });

    }

    上述代码是将map中的value按照逆序排序,如果需要按照升序进行排序的话,只需要修改为o1.getValue() - o2.getValue()即可

  • 相关阅读:
    R语言学习——数据框
    R语言学习——数组
    R语言学习——矩阵
    R语言学习——向量
    SSM的项目结构
    simple-spring-memcached简介
    Arrays
    AbstractCollection 类
    Collections 类
    Map接口
  • 原文地址:https://www.cnblogs.com/lordcheng/p/7300089.html
Copyright © 2011-2022 走看看