[原创]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()即可