首页 > 编程 > Java > 正文

map实现按value升序排序

2019-11-26 15:44:59
字体:
来源:转载
供稿:网友

复制代码 代码如下:

 /**
     * @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;
    }
   

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表