龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

map实现按value升序排序

时间:2014-05-30 02:07来源:网络整理 作者:网络 点击:
分享到:
map内部是按照hash算法存储的,但如果能对map排序在某些时候还是有用的,下面实现对map按照value升序排序,实现对map按照key排序,大家参考使用吧

代码如下:

 /**
     * @param h
     * @return
     * 实现对map按照value升序排序
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByValue(Map h) {
        Set set = h.entrySet();
        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
                .size()]);
        Arrays.sort(entries, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
                Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
                return key1.compareTo(key2);
            }
        });

        return entries;
    }

 /**
     * @param h
     * @return
     * 实现对map按照key排序
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByKey(Map h) {

        Set set = h.entrySet();

        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
                .size()]);

        Arrays.sort(entries, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                Object key1 = ((Map.Entry) arg0).getKey();
                Object key2 = ((Map.Entry) arg1).getKey();
                return ((Comparable) key1).compareTo(key2);
            }

        });

        return entries;
    }
   

精彩图集

赞助商链接