码迷,mamicode.com
首页 > 编程语言 > 详细

对map的值按照由高到低排序

时间:2015-06-27 15:51:08      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

/**
     * 按map中的值由高到低排序
     * @param map
     */
    private Map<String,Integer>  sortMapByValue(Map<String,Integer> map){
        Set<Entry<String, Integer>> entrySet = map.entrySet();
        List<Map.Entry<String, Integer>> entrySetList = new ArrayList<Map.Entry<String, Integer>>(entrySet);
        Collections.sort(entrySetList, new MapValueComparator());
        Map<String, Integer> resultMap = new LinkedHashMap<String,Integer>();
        for(Map.Entry<String, Integer> entry : entrySetList){
            resultMap.put(entry.getKey(), entry.getValue());
        }
        return resultMap;
    }
    
    private class MapValueComparator implements Comparator<Map.Entry<String,Integer>>{
        @Override
        public int compare(Entry<String, Integer> entry0,    Entry<String, Integer> entry1) {
            Integer v0 = entry0.getValue();
            Integer v1 = entry1.getValue();
            return v1.compareTo(v0);
        }
    }

 Map<String,Integer> map  =new  HashMap<String,Integer>();
  map.put("aaa", 1000);
  map.put("bbb", 500);
  map.put("ccc", 2000);
  map.put("ddd", 800);
  map.put("eee", 1500);
 Map<String,Integer> map1= new Test().sortMapByValue(map);
 System.out.println(map1);
int N=3;
        
    Object[] hobbyFlagKeys = map1.keySet().toArray();
    N = Math.min(N, hobbyFlagKeys.length);
    for(int i=0; i<N; i++){
        final String hobbyFlagKey = (String) hobbyFlagKeys[i];
        final Integer count = map1.get(hobbyFlagKey);    
        System.out.println(hobbyFlagKey+":::"+count);
    }
        

 

对map的值按照由高到低排序

标签:

原文地址:http://www.cnblogs.com/52hadoop/p/4603871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!