欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

map实现按value升序排序

程序员文章站 2024-02-19 19:06:46
复制代码 代码如下: /**     * @param h     * @retu...

复制代码 代码如下:

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