要对Map中的key-value键值对进行排序,可以使用Collections类提供的sort方法。该方法允许用户使用自定义的排序方法,可以按键进行排序,或者按值进行排序。

具体代码如下:

1、产生需要的数据

Map<String, Integer> map_Data = new HashMap<String, Integer>();
 map_Data.put("A", 98);
 map_Data.put("B", 50);
 map_Data.put("C", 76);
 map_Data.put("D", 23);
 map_Data.put("E", 85);


2、将Map集合转换成List集合,以便排序

List<Map.Entry<String,Integer>> list_Data = new ArrayList<Map.Entry<String,Integer>>(map_Data.entrySet());


3、开始排序


Collections.sort(list_Data, 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的值进行排序。


采用这种方法,可以对Map类进行排序。

如果要对List进行排序,则直接使用第三步即可实现。