首页 > 编程语言 > 详细

Map 排序

时间:2016-08-05 19:28:37      阅读:109      评论:0      收藏:0      [点我收藏+]

 

  /**
     * 通过map 的 value 排序,并返回排序后的第一个条目
     * 
     * @param m 待排序集合
     * @param desc true:降序排序,false:升序排序
     * @return 返回排序后的第一个条目
     * */
    public Entry<String, Integer> getFristEntryOfSortedMap(Map<String, Integer> m , boolean desc) {
        Entry<String, Integer> entry = null;
        if (m != null && !m.isEmpty()) {
            List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(m.entrySet());
            if(desc){
                Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
                    public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
                        int v1 = 0, v2 = 0;
                        v1 = e1.getValue() == null ? 0 : e1.getValue();
                        v2 = e2.getValue() == null ? 0 : e2.getValue();
                        return v2 - v1;
                    }
                });
            }else{
                Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
                    public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
                        int v1 = 0, v2 = 0;
                        v1 = e1.getValue() == null ? 0 : e1.getValue();
                        v2 = e2.getValue() == null ? 0 : e2.getValue();
                        return v1 - v2;
                    }
                });
            }
            
            Iterator<Entry<String, Integer>> it = entryList.iterator();
            if (it.hasNext()) {
                entry = it.next();
            }
        }
        return entry;
    }

 

Map 排序

原文:http://www.cnblogs.com/zno2/p/5230751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!